2017-07-26 78 views
1

我真的很灰白的頭髮。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

+0

將它分開,首先將'file_get_contents()'的結果存儲在一個變量中,然後'echo'它來查看您實際從服務器返回的結果。如果你把這個添加到你的問題中,也許我們可以明白爲什麼'json_decode()'可能會遇到麻煩。 – rickdenhaan

+2

代碼沒有錯。服務器返回狀態代碼400 –

回答

1

你可以用」不通過參數訪問此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()!

+0

是的,我看到了這一點,抱歉的錯誤。我不知道我們可以將一些選項傳遞給file_get_contents! – Superdrac

3

該空結果的服務器阻止了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字符串,只要。

+0

我認爲這是比CURL解決方案更好的解決方案。此外,我會將您的評論移至您的實際發佈 – GrumpyCrouton

+0

更新並移動。 – bubjavier