Saurabh Borse Saurabh Borse - 7 months ago 25
PHP Question

How to print JSON data in PHP

I want to print these keys "name","adminName1","countryCode" from following JSON result.

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


How to do it right way?

Answer

Just use json_decode and get the values. Because your json_decode function returns an object array you need to use -> for accessing the values.

If your json string name were $json.

$arr = json_decode($json);

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

You json decoded array would be:

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
                )

        )

)