How can I echo a JSON in PHP?

0

Look, I'm doing tests with an api where I'm getting this json:

[
    {
        "id": "bitcoin", 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "rank": "1", 
        "price_usd": "18880.8", 
        "price_btc": "1.0", 
        "24h_volume_usd": "14088000000.0", 
        "market_cap_usd": "316267315150", 
        "available_supply": "16750737.0", 
        "total_supply": "16750737.0", 
        "max_supply": "21000000.0", 
        "percent_change_1h": "-0.74", 
        "percent_change_24h": "1.29", 
        "percent_change_7d": "11.39", 
        "last_updated": "1513649955"
    }
]

I'm doing the code in PHP and would like to echo these things, follow my code (which is not working):

$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/";

$result = file_get_contents($url);

$final = json_decode($result, true);

echo $final->{"price_usd"};

Who knows, could you help me?

Thanks for your attention.

    
asked by anonymous 19.12.2017 / 03:37

2 answers

0

If you look at the JSON , its structure is [{}], this means that JSON is returning an object inside an array.

To access this object, we first have to select the array. That way.

$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/";

$result = file_get_contents($url);

$final = json_decode($result, true);

echo $final[0]["price_usd"]; //Acessamos o primeiro elemento do objeto que está na posição "0" do array e depois acessamos o valor do dele.
    
19.12.2017 / 03:47
0

Return see as an array of objects, as you give json_decode($result, true); it turns an array array. Just do it like this:

echo $final[0]['price_usd'];
    
19.12.2017 / 03:45