2017-02-24 56 views
1

我在wordpress中創建一個插件,它將根據從api收到的數據創建自定義帖子。起初,我有這個代碼:如何在wordpress插件中從外部API檢索數據?

$stuff_request = 'https://thisdomain/api/stuff'; 
    $username = 'thisdomainuser'; 
    $password = 'thisdomainpassword'; 

    $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$password")); 
    $stuff_response = wp_remote_get($stuff_request, array('headers' => $headers)); 

    $stuff_data = json_decode($stuff_response, true); 

,但我收到錯誤 「預計paremter 1是給定的字符串數組」 它向我建議$ stuff_response可能已經在正確的格式返回,所以我從賽季的數據

$stuff_data = $stuff_response; 

但這不能根本沒有錯誤消息出現在調試返回任何刪除的json_decode。這是如何將api調入插件的問題,還是可能是外部api的問題?

+1

'的var_dump($ stuff_response);' – CBroe

+0

或的print_r($ stuff_response); – 2017-02-24 13:49:44

+0

感謝已將此添加到我的插件,並且我返回空 – rmsGreig

回答

0

wp_remote_get返回的響應是一個數組。

試試這個:

$stuff_request = 'https://thisdomain/api/stuff'; 
$username = 'thisdomainuser'; 
$password = 'thisdomainpassword'; 

$headers = array('Authorization' => 'Basic ' . base64_encode("$username:$password")); 
$stuff_response = wp_remote_get($stuff_request, array('headers' => $headers)); 
if(is_array($stuff_response)) { 

    $header = $stuff_response['headers']; // array of http header lines 
    $body = json_decode($stuff_response['body']); // use the content 

} 
+0

謝謝,我已更新我的代碼以匹配上面,並使用上面提出的var_dump,我發現我返回null,任何想法? – rmsGreig

+0

'var_dump($ body);'返回null? –

+0

是的,這是否意味着這是我試圖帶入的json的問題?因爲我相信這個電話現在是正確的? – rmsGreig

相關問題