How can I echo a JSON in PHP?

Asked

Viewed 867 times

1

Look I’m doing some 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 making the code in PHP and would like to echo these things, follow my code (that 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 help me?

Thank you for your attention.

2 answers

1


If you observe the JSON, its structure is [ {} ], which means that JSON is returning an object within an array.

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

$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.

0

The return view as an array of objects, as you give json_decode($result, true); it becomes an array of array. Just do so:

echo $final[0]['price_usd'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.