2 JSON。只有1个工作。 json_decode php
我真的很灰白的头发。2 JSON。只有1个工作。 json_decode php
我想响应为https://api.gdax.com/products/btc-usd/ticker/
的[问]的数据,但它的返回NULL。
当我尝试使用几乎相同的JSON的另一个API,它工作完美。
此示例适用
<?php
$url = "https://api.bitfinex.com/v1/ticker/btcusd";
$json = json_decode(file_get_contents($url), true);
$ask = $json["ask"];
echo $ask;
这个例子返回null
<?php
$url = "https://api.gdax.com/products/btc-usd/ticker/";
$json = json_decode(file_get_contents($url), true);
$ask = $json["ask"];
echo $ask;
任何人那里有一个很好的解释,什么是错的代码返回null
你可以用”不通过参数访问此URL。当主机正在检查请求来自何处时,会发生这种情况。
$ch = curl_init();
$header=array('GET products/btc-usd/ticker/ HTTP/1.1',
'Host: api.gdax.com',
'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language:en-US,en;q=0.8',
'Cache-Control:max-age=0',
'Connection:keep-alive',
'Host:adfoc.us',
'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
);
curl_setopt($ch,CURLOPT_URL,"https://api.gdax.com/products/btc-usd/ticker/");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
$result=curl_exec($ch);
然后你可以在$ result上使用json_decode()!
是的,我看到了这一点,抱歉的错误。我不知道我们可以将一些选项传递给file_get_contents! – Superdrac
该空结果的服务器阻止了php代理连接,从而返回http 400错误。您需要为您的http请求指定一个user_agent值。
例如
$ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36';
$options = array('http' => array('user_agent' => $ua));
$context = stream_context_create($options);
$url = "https://api.gdax.com/products/btc-usd/ticker/";
$json = json_decode(file_get_contents($url, false, $context), true);
$ask = $json["ask"];
echo $ask;
你也可以为你确保你的目标服务器允许它使用的$ua
变量任何你想要的USER_AGENT字符串,只要。
我认为这是比CURL解决方案更好的解决方案。此外,我会将您的评论移至您的实际发布 – GrumpyCrouton
更新并移动。 – bubjavier
将它分开,首先将'file_get_contents()'的结果存储在一个变量中,然后'echo'它来查看您实际从服务器返回的结果。如果你把这个添加到你的问题中,也许我们可以明白为什么'json_decode()'可能会遇到麻烦。 – rickdenhaan
代码没有错。服务器返回状态代码400 –