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():
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);
- To get a PHP object:
Access the
matchesdata
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']);
- If you went with an object:
推荐:添加错误检查
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

