Reputation: 2272
I have called one webservice using the below code. Now I want to echo some value from it. But I am not able to . I tried some option but they didnt worked.
<?php
$api_url = "myurl";
$response = file_get_contents($api_url);
$my_array = json_decode($response, true);
?>
the above code gives me JSON resonse
{
"places":{
"place":[
{
"place_id":"FHa5VXVTU7MbX9qW",
"woeid":"2192348",
"latitude":"32.433",
"longitude":"74.366",
"place_url":"\/Pakistan\/Punjab\/Bhopalwala",
"place_type":"locality",
"place_type_id":"7",
"timezone":"Asia\/Karachi",
"name":"Bhopalwala, Punjab, Pakistan",
"woe_name":"Bhopalwala"
}
],
"latitude":"32.45",
"longitude":"74.34",
"accuracy":"16",
"total":1
},
"stat":"ok"
}
I tried to echo woe_name.
echo $my_array['places']['place']['woe_name'];
print $my_array->places["0"]->place->woe_name;
Here is var_dump
array(2) {
["places"]=>
array(5) {
["place"]=>
array(1) {
[0]=>
array(10) {
["place_id"]=>
string(16) "FHa5VXVTU7MbX9qW"
["woeid"]=>
string(7) "2192348"
["latitude"]=>
string(6) "32.433"
["longitude"]=>
string(6) "74.366"
["place_url"]=>
string(27) "/Pakistan/Punjab/Bhopalwala"
["place_type"]=>
string(8) "locality"
["place_type_id"]=>
string(1) "7"
["timezone"]=>
string(12) "Asia/Karachi"
["name"]=>
string(28) "Bhopalwala, Punjab, Pakistan"
["woe_name"]=>
string(10) "Bhopalwala"
}
}
["latitude"]=>
string(5) "32.45"
["longitude"]=>
string(5) "74.34"
["accuracy"]=>
string(2) "16"
["total"]=>
int(1)
}
["stat"]=>
string(2) "ok"
}
How can I do it?
Upvotes: 0
Views: 10684
Reputation: 4043
Looks like your JSON is missing a curly brackey - you need to create one at the beginning, it's missing a
'{' before "places"
Upvotes: 0
Reputation: 1155
Try:
echo $my_array['places']['place'][0]['woe_name'];
If the second parameter of json_decode is true
it will return an array. You can use var_dump to check a varables type if you're not sure.
In Json, curly braces {}
are used for objects with "key": value
pairs, square braces []
are used for arrays of objects.
Upvotes: 1
Reputation: 1319
It misses a {
in the beginning of your json.
With it, it gives:
$my_array['places']['place'][0]['woe_name']
Upvotes: 1
Reputation: 318182
$my_array = json_decode($response);
$my_array->places->place[0]->woe_name;
my_array
contains an object, places
contains an object, place
contains an array with a nested object.
Upvotes: 4