Andrew Christopher Andrew Christopher - 3 months ago 8
JSON Question

ECHO JSON WITH PHP

I have this json and I need to echo some specific results from it with php

JSON

{
totalResultsCount: 1,
geonames: [
{
adminCode1: "06",
lng: "27.85849",
geonameId: 953781,
toponymName: "Soweto",
countryId: "953987",
fcl: "P",
population: 1695047,
countryCode: "ZA",
name: "Soweto",
fclName: "city, village,...",
countryName: "South Africa",
fcodeName: "populated place",
adminName1: "Gauteng",
lat: "-26.26781",
fcode: "PPL"
}
]
}


How would I echo lets say name which is in geonames[]

I tried this

<?php

echo $json->geonams->name
?>

Answer

You can use json object in two ways:

1. json object style:

echo $json->geonams->name;

2. array style:

$arr = json_decode($json, true);    // it will return an array
echo $arr['geonams']['name'];
Comments