Reputation: 33
I'm trying to display some elements from some json data at the following URL using the following code, but it isn't displaying anything. Any ideas what I'm doing wrong?
<?php
$url="http://fbclaurel.onthecity.org/plaza/events?format=json";
$data = file_get_contents($url);
$json = json_decode($data);
foreach($json->"global_event" as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
?>
Upvotes: 0
Views: 93
Reputation: 4370
do it like below
$url="http://fbclaurel.onthecity.org/plaza/events?format=json";
$data = file_get_contents($url);
$json = json_decode($data);
//echo '<pre>';
//print_r( $json[0]->global_event);
array_walk_recursive($json[0]->global_event, function ($a,$b){
echo 'KEY :'.$b.' & Value :'.$a.'<br>';
});
OUTPUT
KEY :starting_at & Value :2014-06-01T08:00:00-04:00
KEY :external_form_id & Value :
KEY :short_url & Value :http://bit.ly/1jOTqao
KEY :body & Value : Hymns are led by piano and organ. The choral music is sung by the Chapel Choir and the sermon message is given by Pastor Stan.
KEY :ending_at & Value :2014-06-01T09:00:00-04:00
KEY :euid & Value :9ea33765449eb1476530c84d44a01cf200709cf9
KEY :title & Value :Classic Worship Service
KEY :updated_at & Value :2014-05-25T22:28:24-04:00
KEY :created_at & Value :2014-05-25T22:28:23-04:00
Upvotes: 0
Reputation: 165069
You actually have a syntax error that is probably hidden due to your configured error reporting / display settings. It would be something like this
PHP Parse error: syntax error, unexpected '"global_event"' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
When developing, I recommend you always have the following properties in php.ini
display_errors = On
error_reporting = E_ALL
I've just checked the data from that API and it returns an array. Each array entry is an object with a single global_event
property that is itself, another object. I imagine you're going to need something like this to iterate...
$json = json_decode($data, true);
// the second "true" argument forces an array format result.
// I find it more appropriate when iterate keys or when keys
// might be invalid property names.
foreach ($json as $obj) {
$globalEvent = $obj['global_event'];
// now $globalEvent is an array with keys such as
// addresses, body, created_at, ending_at, etc.
// Note that few of these properties are simple, scalar values (like strings),
// most are arrays themselves
// display example...
echo 'title: ', htmlspecialchars($globalEvent['title']), '<br>',
'short_url: ', htmlspecialchars($globalEvent['short_url']), '<br>';
}
Upvotes: 3