PHP cURL请求报错stdClass类对象无法转换为字符串如何解决
错误原因
- 服务端返回的JSON外层是索引数组,每个元素是单条用户数据的对象。你调用
json_decode($resp)时未传第二个参数,默认返回stdClass类型对象而非关联数组。 - 直接遍历最外层返回结果时,循环中拿到的
$val是单条用户的stdClass对象,PHP不支持直接将对象拼接进字符串输出,因此触发报错。
修复方案
方案1:转为关联数组嵌套遍历
将json_decode的第二个参数设为true,把返回结果全部转为关联数组,再嵌套遍历输出:
// 替换原cURL代码中的else分支 } else { $decoded = json_decode($resp, true); // 遍历外层用户数组 foreach($decoded as $index => $user) { echo "第".($index + 1)."个用户信息:<br>"; // 遍历单个用户的属性 foreach($user as $key => $val) { echo $key . ': ' . $val . '<br>'; } echo '<hr>'; } }
方案2:保持对象格式直接读取属性
如果不想转关联数组,也可以直接读取stdClass对象的对应属性输出:
// 替换原cURL代码中的else分支 } else { $decoded = json_decode($resp); foreach($decoded as $index => $user) { echo "第".($index + 1)."个用户信息:<br>"; echo 'username: ' . $user->username . '<br>'; echo 'fullname: ' . $user->fullname . '<br>'; echo 'email: ' . $user->email . '<br>'; echo '<hr>'; } }
内容的提问来源于stack exchange,提问作者John Beasley
相关产品推荐
相关产品推荐

