You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用Guzzle请求API后JSON解析错误求助

解决访问$return_values->matches报错的问题

Hey there, let's break down why you're hitting that error and how to fix it:

问题根源

When you use $res->getBody()->getContents(), what you're getting back is a raw JSON string, not a PHP object or array. That's why trying to access ->matches directly throws an error—strings don't have object properties to access!

修复步骤

You need to parse the JSON string into a usable PHP structure first using json_decode():

  1. Parse the JSON string
    Pick either a PHP object or associative array based on your preference:

    • To get a PHP object:
      $data = json_decode($return_values);
      
    • To get an associative array:
      $data = json_decode($return_values, true);
      
  2. Access the matches data
    Now you can retrieve the matches correctly:

    • If you went with an object:
      print_r($data->matches);
      
    • If you went with an array:
      print_r($data['matches']);
      

推荐:添加错误检查

To avoid unexpected issues, it's smart to verify the JSON parsed successfully and that the matches field exists:

$data = json_decode($return_values);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON parsing failed: " . json_last_error_msg();
} else {
    if (isset($data->matches)) {
        print_r($data->matches);
    } else {
        echo "No 'matches' field found in the API response";
    }
}

内容的提问来源于stack exchange,提问作者Bijaya Kumar Oli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:56:28