Coinage
Coinage

Reputation: 1

Unable to extract data from JSON with PHP

I am unable to get data price_usd to display on a page from the below

<?php

$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
$json = json_decode(file_get_contents($url), true);
$price = $json["price_usd"];
echo $price;
?>

Not sure what it is that I am doing incorrectly.

[
    {
        "id": "bitcoin", 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "rank": "1", 
        "price_usd": "2451.36", 
        "price_btc": "1.0", 
        "24h_volume_usd": "726987000.0", 
        "market_cap_usd": "40298274744.0", 
        "available_supply": "16439150.0", 
        "total_supply": "16439150.0", 
        "percent_change_1h": "-1.7", 
        "percent_change_24h": "-3.89", 
        "percent_change_7d": "-4.33", 
        "last_updated": "1499697854"
    }
]

Thanks

Coinage

Upvotes: 0

Views: 36

Answers (1)

Mohanad Kaleia
Mohanad Kaleia

Reputation: 791

Your JSON object $json comes as an array with one item, To get the price_usd try:

$price = $json[0]["price_usd"];

Upvotes: 1

Related Questions