這是我的代碼,我試圖顯示來自遠程 API 的值,我試圖通過 Wordpress 中的 .php 檔案獲取這些值。
<?php
try {
$response = wp_remote_get( 'MYURLHERE', array(
'headers' => array(
'Accept' => 'application/json',
)
) );
if ( ( !is_wp_error($response)) && (200 === wp_remote_retrieve_response_code( $response ) ) ) {
$result = json_decode( wp_remote_retrieve_body( $response, true) );
echo $result['data']['0']['id'];
}
} catch( Exception $ex ) {
//Handle Exception.
}
?>
收到以下錯誤:
Fatal error: Uncaught Error: Cannot use object of type stdClass as array
我究竟做錯了什么?
這應該是陣列:
Array
(
[data] => Array
(
[0] => Array
(
[id] => 124
[name] => MyName
[supertype] => Mso
uj5u.com熱心網友回復:
在 PHP 手冊中可以看到 JSON Function 的引數:https ://www.php.net/manual/en/function.json-decode.php
這 json_decode 代碼行是錯誤的,這里是修復:
$result = json_decode( wp_remote_retrieve_body( $response), true );
uj5u.com熱心網友回復:
您必須輸出一個與您得到錯誤的變數不同的變數。
這是因為您使用 json_decode() 沒有任何引數。這意味著它將作為物件而不是陣列輸出。
因此,您顯示的示例輸出必須來自$result您嘗試回顯的其他地方。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/519583.html
