如何使用PHP获取和解码JSON数据?

时间:2017-03-21 19:15:59

标签: php json curl decode file-get-contents

我如何获得变量" price_usd"和" price_btc"来自JSON url https://api.coinmarketcap.com/v1/ticker/ethereum/?我写了一个脚本但没有任何反应。

 <?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;
?>

2 个答案:

答案 0 :(得分:3)

你的代码使用了两次file_get_contents,看看会是:

<?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;
?>

答案 1 :(得分:0)

试试这个

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

?>