我正在尝试从各种来源解析rss供稿,其中一个来源是:http://feeds.feedburner.com/DiscoveryNews-Top-Stories
但是这个消息来源给了我一些奇怪的json数据:
"item": [
{
"title": [
"Snazzy Science Photos of the Week (August 10-16)",
{
"type": "html",
"content": "Snazzy Science Photos of the Week (August 10-16)"
}
],
"description": [
"Glowing rabbits, treasure-hunting badgers and a case of mistaken UFO identity help round out this week's photos.<img src=\"http://feeds.feedburner.com/~r/DiscoveryNews-Top-Stories/~4/S6Urfvdw2DQ\" height=\"1\" width=\"1\"/>",
{
"type": "html",
"content": "Glowing rabbits, treasure-hunting badgers and a case of mistaken UFO identity help round out this week's photos."
}
],
目前,我正在使用以下代码来获取帖子的标题:
if(isset($jit->title->content)){
$title = $decoded_json->query->results->item->title->content;
}else{
$title = $decoded_json->query->results->item->title;
}
但是当我尝试解析Discovery新闻源时,上面的代码失败了。请帮忙吗?
[编辑]: 我正在使用YQL从源代码获取等效的JSON。这是link
答案 0 :(得分:1)
它将元素打包为数组:
"title": [
"No Battery Required for This Wireless Device",
{
"type": "html",
"content": "No Battery Required for This Wireless Device"
}
],
您可以阅读第一个元素:
<?php
$url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url=%22http://feeds.feedburner.com/DiscoveryNews-Top-Stories%22&format=json&diagnostics=true&callback=cbfunc';
$data = substr(file_get_contents($url), 7, -2);
$json = json_decode($data);
foreach ($json->query->results->item as $item)
{
echo "Title: ", $item->title[0], "\nDescription: ", $item->description[0], "\n";
echo "==================================================\n\n";
}
或使用SimpleXML库:
$url = 'http://feeds.feedburner.com/DiscoveryNews-Top-Stories?format=xml';
$xml = simplexml_load_string(file_get_contents($url));
foreach ($xml->channel->item as $item)
{
echo "Title: ", $item->title, "\nDescription: ", $item->description, "\n";
echo "==================================================\n\n";
}