我正在尝试使用PHP在google map API中显示来自附近(景点)搜索的一张照片。我是JSON的新手,因此无法在同一位置进行完全编码。
来自Google的Json响应如下:
"results" : [
{
"formatted_address" : "262 Pasir Panjang Road, Singapore 118628",
"geometry" : {
"location" : {
"lat" : 1.2842878,
"lng" : 103.7824933
},
"viewport" : {
"northeast" : {
"lat" : 1.285510029892722,
"lng" : 103.7832685
},
"southwest" : {
"lat" : 1.282810370107278,
"lng" : 103.7801677
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "db6bd077825e5ddba7aa0340226a298de72d6aab",
"name" : "Haw Par Villa",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 666,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/111959044965723437057/photos\"\u003eAyush Basu\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAkDM0lgMa66jbH8lAHKmY0-h7kR-dgMj9uoF3sTwGEVI3hPyAK6jczfLd1HLpNV5V9-KjMDW5ncoYeY9SMoR-HklvQ2RMW8aUSBGOrmtH9xI7bPnU_riuDUZMTfKMVV3kEhBxEyaQLTwpuE9OaKiSBl_uGhRpop1RlhssCcrUHwka5s_ND7HoRA",
"width" : 1000
}
我的PHP代码如下:
$curl_loc = curl_init();
curl_setopt($curl_loc,CURLOPT_HTTPHEADER,array("Content-Type: application/json", "Accept: application/json"));
curl_setopt ($curl_loc, CURLOPT_URL, "https://maps.googleapis.com/maps/api/place/textsearch/json?query=$dest_name1%20places%20of%20interest&language=en&key=APIKEY");
curl_setopt($curl_loc, CURLOPT_RETURNTRANSFER, 1);
$dest_loc_xml = curl_exec ($curl_loc);
if ($dest_loc_xml === false) {
die('Error fetching data: ' . curl_error($curl_loc));
}
curl_close ($curl_loc);
//echo htmlspecialchars("$dest_hotel_xml", ENT_QUOTES);
$data = json_decode($dest_loc_xml);
foreach ($data->results as $result){
<?php echo $result->name; ?>
<?php echo $result->photo_reference; ?>
}
我能够正确检索'name'的值,但我无法检索'photo_reference'的值。它是一个PHP脚本问题。谁能在这方面帮助我。预先谢谢你。
答案 0 :(得分:1)
您无法直接获取photo_reference的属性,因为它存在于“照片”数组中。
$data = json_decode($dest_loc_xml);
foreach ($data->results as $result){
<?php echo $result->name; ?>
if(isset($result->photos)) {
foreach ($result->photos as $res){
<?php echo $res->photo_reference; ?>
}
}
}