user9804375
user9804375

Reputation:

Trying to extract data from json google API using PHP

I am trying to display one photo from a nearby (places of interest) search in the google map API using PHP. I am new to json so not able to exactly code on the same.

The Json response from Google is as follows:

    "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
        }

My PHP code is as follows:

 $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; ?>
   }

Iam able to retrieve the value of 'name' properly, but i am not able to retrieve the value of 'photo_reference'. Its a php scripting problem. Can anyone pls help me on this. Thank you in advance.

Upvotes: 0

Views: 289

Answers (1)

Ved
Ved

Reputation: 746

You cannot get property of photo_reference directly because it is present inside "photos" array.

   $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; ?>
           }
       }
   }

Upvotes: 1

Related Questions