简体   繁体   中英

How to use PHP to fetch and decode JSON data?

How can I get variables "price_usd" and "price_btc" from JSON url https://api.coinmarketcap.com/v1/ticker/ethereum/ ? I wrote a script but nothing happens.

 <?php
$tick = file_get_contents('https://api.coinmarketcap.com/v1/ticker/ethereum/'); 
$url = $tick;
$json = file_get_contents($url);
$data = json_decode($json, TRUE);

$usd = $data[0]["price_usd"];
echo $usd;
?>

Your code use a file_get_contents twice, look at would be:

<?php
$tick = file_get_contents('https://api.coinmarketcap.com/v1/ticker/ethereum/');
$url = $tick;
echo $url;
//$json = file_get_contents($url);
$data = json_decode($tick, TRUE);

$usd = $data[0]["price_usd"];
echo $usd;
?>

Try this

<?php
$json = file_get_contents('https://api.coinmarketcap.com/v1/ticker/ethereum/'); 
$data = json_decode($json);
var_dump($data[0]->price_usd);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM