在PHP中解析json字符串

时间:2014-02-01 10:03:35

标签: php json

    {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "New Delhi",
               "short_name" : "New Delhi",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "West Delhi",
               "short_name" : "West Delhi",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Delhi",
               "short_name" : "DL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "New Delhi, Delhi, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.88981589999999,
                  "lng" : 77.34181459999999
               },
               "southwest" : {
                  "lat" : 28.4010669,
                  "lng" : 76.8396999
               }
            },
            "location" : {
               "lat" : 28.635308,
               "lng" : 77.22496
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.88981589999999,
                  "lng" : 77.34181459999999
               },
               "southwest" : {
                  "lat" : 28.4010669,
                  "lng" : 76.8396999
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

如何用php解析上面的json字符串

尝试以下代码但没有成功:

   $url = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=Delhi&sensor=true");


     $json = json_decode($url);


foreach($json->results as $item) {
        $location_item = array(
            'address' => $item->formatted_address,

        );

    }

我得到空白页面代码不起作用请帮助我是php的新手

1 个答案:

答案 0 :(得分:0)

  

我得到空白页面代码不起作用请帮助我是新手   PHP

您的代码确实有效,也许您不打印数据,这就是您获得空白页的原因。

测试

<?php
$url = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=Delhi&sensor=true");
$json = json_decode($url);
foreach($json->results as $item) {
    $location_item = array(
        'address' => $item->formatted_address,

    );

}

print_r($location_item);

<强> OUTPUT :

Array
(
    [address] => New Delhi, Delhi, India
)