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

PHP调用Google Places API获取场所名称失败问题排查

Fixing Your Google Places API Result Extraction

Hey there, let's get this sorted out—you're just a couple of small tweaks away from getting that "Biaggio Cafe" result you're expecting! Here's what's going wrong in your code, and how to fix it:

1. You're treating an array like an object

When you use json_decode($string, true), the second parameter true tells PHP to convert the JSON response into an associative array, not a PHP object. That means you can't use the -> syntax to access properties—you need to use array bracket notation ([]) instead.

2. echo print_r(...) is causing the {1} output

print_r() by default prints content directly to the output, and it returns a boolean value (true) when it succeeds. When you wrap that in echo, you're actually printing that boolean (which gets converted to 1), not the value you want. Also, the name field is a string, not an array—so adding [0] to it is unnecessary (and would just grab the first character of the name if it worked).


Here's the corrected code:

$string = file_get_contents("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&types=food&key=AIzaSyCpOG91fkAzPTZiFq7G9HbLfbmVyW8Wgyc");
$json_a = json_decode($string, true);

// Add a quick check to avoid errors if no results exist
if (!empty($json_a['results']) && isset($json_a['results'][0]['name'])) {
    echo $json_a['results'][0]['name']; // This will output "Biaggio Cafe"
} else {
    echo "No valid results or name field found";
}

A quick breakdown of the fixes:

  • Swapped $json_a->results[0]->name[0] for $json_a['results'][0]['name'] to match the associative array structure.
  • Removed the print_r() wrap and just echo the name directly—no extra output from print_r's return value.
  • Added error checking to handle cases where the API returns no results, or the name field is missing (prevents PHP warnings/errors).

内容的提问来源于stack exchange,提问作者mohammed khuly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:22:03