1

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

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

4

1 回答 1

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.

}

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

于 2013-04-20T13:58:49.350 回答