问题
I have the following JSON content that I'm pulling from a service feed:
[
{
"global_event":{
"ending_at":"2011-11-07T02:00:00Z",
"short_url":"http://bit.ly/reAhRw",
"created_at":"2011-10-04T14:25:41Z",
"event_responses":[
],
"addresses":{
"location":{
"city":"blah",
"latitude":30.205288,
"zipcode":"343434",
"street":"blah",
"longitude":-95.475289,
"state":"TX"
}
},
"body":"blahblahblah",
"euid":"2f489d0c82d167f1c16aba5d3b4c29ade6f1d52a",
"title":"Fusion",
"updated_at":"2011-10-04T14:26:57Z",
"event_roles":[
],
"user":{
"long_name":"Fusion Single",
"nickname":""
},
"event_items":[
],
"starting_at":"2011-11-07T00:00:00Z"
}
}
]
I've tried the following code to parse it to no avail:
$json = @file_get_contents('jsonfeed');
$feed = json_decode($json);
foreach($feed->global_event as $item) {
$rss_item = array(
'title' => $item->title,
'link' => $item->short_url,
'author' => $item->long_name,
'content' => $item->body,
'date' => $item->updated_at,
'type' => 'Woodlands Church'
);
array_push($this->rss, $rss_item);
}
The final array that is created $this->rss never has anything in it and is just a null array. Any ideas?
回答1:
In JSON, curly brackets ("{" and "}") define objects, not arrays. Angle brackets define arrays.
so $feed is an array, containing 1 object with 1 property called global_event.
the loop should be:
$feed = json_decode($json);
foreach($feed as $obj) {
$item = $obj->global_event;
$rss_item = array(
'title' => $item->title,
'link' => $item->short_url,
'author' => $item->long_name,
'content' => $item->body,
'date' => $item->updated_at,
'type' => 'Woodlands Church'
);
array_push($this->rss, $rss_item);
}
回答2:
You need to parse it this way:
<?php
$json = @file_get_contents("jsonfeed");
$feed = json_decode($json);
foreach($feed as $item) {
// your code, accessing everything by using
// $item->global_event->PROPERTY
}
?>
because at the beginning of your foreach loop your $feed variable looks like this:
Array
(
[0] => stdClass Object
(
[global_event] => stdClass Object
(
[ending_at] => 2011-11-07T02:00:00Z
[short_url] => http://bit.ly/reAhRw
[created_at] => 2011-10-04T14:25:41Z
[event_responses] => Array
(
)
[addresses] => stdClass Object
(
[location] => stdClass Object
(
[city] => blah
[latitude] => 30.205288
[zipcode] => 343434
[street] => blah
[longitude] => -95.475289
[state] => TX
)
)
[body] => blahblahblah
[euid] => 2f489d0c82d167f1c16aba5d3b4c29ade6f1d52a
[title] => Fusion
[updated_at] => 2011-10-04T14:26:57Z
[event_roles] => Array
(
)
[user] => stdClass Object
(
[long_name] => Fusion Single
[nickname] =>
)
[event_items] => Array
(
)
[starting_at] => 2011-11-07T00:00:00Z
)
)
)
Make sure to pay attention to what's an object and what's an array so you use the appropriate methods to access the data (so, objects with -> notation and arrays with [] notation).
来源:https://stackoverflow.com/questions/7889738/json-parsing-with-php