Reputation: 573
I want to echo an array data from json decode result, so I have tried both the file_get_contents and also curl which works.
This is the response I get from the server which is json output..
{"Servers": {
"lastChangedDate": null,
"ServersList": [
{
"online": "The server is UP",
"offline": "The server is DOWN",
"maintainace": "The server is currently in maintenance mode",
"location": "EU",
"ip": "x.x.x.x"
},
{
"online": "The server is UP",
"offline": "The server is DOWN",
"maintainace": "The server is currently in maintenance mode",
"location": "US",
"ip": "x.x.x.x"
}
]
}}
now then the output will be an array like this after decoding it..
Array (
[Servers] => Array (
[lastChangedDate] =>
[ServersList] => Array (
[0] => Array (
[online] => The server is UP
[offline] => The server is down
[maintenance] => The server is currently in maintenance mode
[location] => EU
[ip] => x.x.x.x
)
[1] => Array (
[online] => The server is UP
[offline] => The server is DOWN
[maintenance] => The server is currently in maintenance mode
[location] => US
[ip] => x.x.x.x
)
)
)
)
Here is my php code
<?php
$request = file_get_contents("test.json");
$input = json_decode($request, true);
echo $input['Servers']['lastChangedDate']['ServersList'][0]['online'];
?>
demo with print_r ($input); instead of echo http://phpad.org/run/1666334020
So in my main page I want to output to be like this http://codepen.io/anon/pen/jEEPMG.html
Upvotes: 1
Views: 562
Reputation: 5957
Entries $input['Servers'];
and $input['lastChangedDate'];
are on the same level in the array, so you can't access$input['Servers']['lastChangedDate']
.
I think you're trying to do:
$input['Servers']['ServersList'][0]['online'];
Upvotes: 1
Reputation: 2572
in the json you posted above 'lastChangedDate' is null means you can't access it with
$input['Servers']['lastChangedDate']['ServersList'][0]['online'];
First you should find why lastChangedDate is null. $input['Servers']['lastChangedDate']['ServersList'][0]['online'];
The bold text is where the access conflict begins. PHP should also output you an error like "Undefined index: ServerList" so you need to first fill lastChangedDate to make further requests to its content
Could it be you wanted to access
$input['Servers']['ServersList'][x]['online'];
Upvotes: 1