PHP调用Google Places API获取场所名称失败问题排查
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 justechothe name directly—no extra output fromprint_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

