如何在PHP中打印JSON数据

时间:2016-05-07 15:13:46

标签: php json

我想从以下JSON结果中打印这些键“name”,“adminName1”,“countryCode”。

{
"geonames": [{
    "adminCode1": "16",
    "lng": "74.19774",
    "distance": "2.95838",
    "geonameId": 1254611,
    "toponymName": "Thengode",
    "countryId": "1269750",
    "fcl": "P",
    "population": 0,
    "countryCode": "IN",
    "name": "Thengode",
    "fclName": "city, village,...",
    "countryName": "India",
    "fcodeName": "populated place",
    "adminName1": "Maharashtra",
    "lat": "20.51997",
    "fcode": "PPL"
}]
}

如何正确地做到这一点?

3 个答案:

答案 0 :(得分:1)

非常简单,请查看。

<?php 

//just for error loggin
error_reporting(1);
ini_set('display_errors', true);

//json data
$json = '{
"geonames": [{
    "adminCode1": "16",
    "lng": "74.19774",
    "distance": "2.95838",
    "geonameId": 1254611,
    "toponymName": "Thengode",
    "countryId": "1269750",
    "fcl": "P",
    "population": 0,
    "countryCode": "IN",
    "name": "Thengode",
    "fclName": "city, village,...",
    "countryName": "India",
    "fcodeName": "populated place",
    "adminName1": "Maharashtra",
    "lat": "20.51997",
    "fcode": "PPL"
}]}';

//decoded json object
$jsonDataObject = json_decode($json);

//parsed variables
$name = $jsonDataObject->geonames[0]->name;
$adminName1 = $jsonDataObject->geonames[0]->adminName1;
$countryCode = $jsonDataObject->geonames[0]->countryCode;
?>

答案 1 :(得分:0)

只需使用json_decode并获取值即可。由于您的json_decode函数返回一个对象数组,因此您需要使用->来访问这些值。

如果您的json字符串名称为$json

$arr = json_decode($json);

echo $arr->geonames[0]->name; //Thengode
echo $arr->geonames[0]->adminName1; //Maharashtra
echo $arr->geonames[0]->countryCode; //IN

你json解码数组将是:

stdClass Object
(
    [geonames] => Array
        (
            [0] => stdClass Object
                (
                    [adminCode1] => 16
                    [lng] => 74.19774
                    [distance] => 2.95838
                    [geonameId] => 1254611
                    [toponymName] => Thengode
                    [countryId] => 1269750
                    [fcl] => P
                    [population] => 0
                    [countryCode] => IN
                    [name] => Thengode
                    [fclName] => city, village,...
                    [countryName] => India
                    [fcodeName] => populated place
                    [adminName1] => Maharashtra
                    [lat] => 20.51997
                    [fcode] => PPL
                )

        )

)

答案 2 :(得分:-1)

$json = '{
"geonames": [{
    "adminCode1": "16",
    "lng": "74.19774",
    "distance": "2.95838",
    "geonameId": 1254611,
    "toponymName": "Thengode",
    "countryId": "1269750",
    "fcl": "P",
    "population": 0,
    "countryCode": "IN",
    "name": "Thengode",
    "fclName": "city, village,...",
    "countryName": "India",
    "fcodeName": "populated place",
    "adminName1": "Maharashtra",
    "lat": "20.51997",
    "fcode": "PPL"
}]
}';

$data = json_decode($json);
echo $data->geonames[0]->name;