WordPress中PHP获取远程API值报错:无法将stdClass作为数组使用
问题分析与解决
错误根源
你把json_decode的**关联数组转换参数true**错传给了wp_remote_retrieve_body函数,导致json_decode默认返回stdClass对象,但你却用数组下标去访问,因此触发了类型错误。
修正后的代码
<?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 ) ) { // 将true传给json_decode,而非wp_remote_retrieve_body $result = json_decode( wp_remote_retrieve_body( $response ), true ); echo $result['data'][0]['id']; } } catch( Exception $ex ) { // 可在此添加错误处理逻辑,比如: // echo '数据获取失败:' . $ex->getMessage(); } ?>
关键说明
wp_remote_retrieve_body($response)仅需传入响应对象,第二个参数是控制是否返回原始二进制数据的可选参数(默认false),不需要传true。json_decode($json_string, true)的第二个参数为true时,会将JSON解析为关联数组,这样你就能用['data'][0]['id']的数组语法访问数据。- 如果不传
true,json_decode默认返回stdClass对象,此时需要用对象语法访问:$result->data[0]->id,但根据你的预期结构,数组方式更匹配需求。
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

