使用 PHP 解析 JSON
我从服务提要中提取了以下 JSON 内容:
[
{
"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"
}
}
]
我已尝试使用以下代码来解析它,但无济于事:
$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);
}
创建的最终数组 $this->rss
从不里面有任何东西,只是一个空数组。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 JSON 中,大括号(“{”和“}”)定义对象,而不是数组。尖括号定义数组。
所以
$feed
是一个数组,包含 1 个对象和 1 个名为global_event
的属性。循环应该是:
In JSON, curly brackets ("{" and "}") define objects, not arrays. Angle brackets define arrays.
so
$feed
is an array, containing 1 object with 1 property calledglobal_event
.the loop should be:
您需要这样解析它:
因为在
foreach
循环的开头,您的$feed
变量如下所示:确保注意什么是对象,什么是对象数组,因此您可以使用适当的方法来访问数据(因此,带有 -> 表示法的对象和带有 [] 表示法的数组)。
You need to parse it this way:
because at the beginning of your
foreach
loop your$feed
variable looks like this: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).