简体   繁体   English

在PHP中解析JSON字符串

[英]Parse json string in php

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

How do i parse the above json string with php 如何使用php解析上述json字符串

Trying the following code out but no success: 试用以下代码,但没有成功:

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

        );

    }

I am getting blank page the code doesn't work please help i am new to php 我正在获取空白页代码无法正常工作,请帮助我是php新手

I am getting blank page the code doesn't work please help i am new to php 我正在获取空白页代码无法正常工作,请帮助我是php新手

Your code actually works , maybe you are not printing the data that is why you are getting a blank page. 您的代码实际上有效,也许您没有打印数据,这就是为什么您得到空白页的原因。

Tested 经测试

<?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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM