2013-04-20 160 views
1

我想如何存储酒店名称和位置,由google提供的响应位置在PHP数组中。如果我的搜索字符串是餐馆在纽约解析来自Google Place API响应的数据(Json格式)

api的响应是json格式。

我发送搜索请求脚本是:

<?php 
    if(isset($_GET['text'])) 
    { 
     if(!empty($_GET['text'])) 
     { 
      $search_text=strip_tags($_GET['text']); 

      $hostname = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=$search_text&sensor=true&key=AIzaSyDVdJtIAvhmHE7e2zoxA_Y9qWRpp6eE2o8"; 


      // read the post from PayPal system and add 'cmd' 


      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_URL, "$hostname"); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 

      $res = curl_exec($ch); 
      curl_close($ch); 

      if(!$res) 
      { 
       // error log 
       echo'Unable to find results.'; 
      } else {  
       **// ALL output printing code goes down here** 
       //$res=json_decode($res); 
       //var_dump(json_decode($res)); 
       $obj=var_dump(json_decode($res, true)); 
       print_r($obj['"results']); 




       } 
     } else { 
      echo'<h4><font color="red">Please enter the text to search.</font></h4>'; 
      } 
    } 
?> 

好了,上面代码的输出是什么JSON格式。但我需要从json输出中检索餐厅的名称和它们的位置。

所以,请给我一种方法来提取确切的输出。

+0

作为一个小方面的说明,请尝试file_get_contents()而不是CURL。这很容易。 例如: $ results = json_decode(file_get_contents($ hostname),TRUE); – 2013-04-20 14:00:59

回答

2

正如我所看到的结果键包含您需要的数据的数组。 就这样做:

$jsonContent = json_decode($res, true); 

foreach ($jsonContent['results'] as $result) { 

    // now you have the $result array that contains the location of the place 
    // and the name ($result['formatted_address'], $result['name']) and other data. 

} 

我希望你知道什么,从这个角度做。