【问题标题】:Parse the data from Google Place api response in (Json format)以(Json 格式)解析来自 Google Place api 响应的数据
【发布时间】:2013-04-20 13:27:39
【问题描述】:

我想如何将 google place api 提供的响应中的酒店名称和位置存储在 PHP 数组中。如果我的搜索字符串是 restaurant in New York

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 输出中检索餐厅的名称及其位置。

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

【问题讨论】:

  • 作为一个小注解,尝试使用 file_get_contents() 而不是 CURL。这要容易得多。示例:$results = json_decode(file_get_contents($hostname), TRUE);

标签: php json curl google-places-api


【解决方案1】:

正如我所见,结果键包含包含您需要的数据的数组。 只需执行以下操作:

$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.

}

我希望你从这一点上知道该怎么做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多