0

我正在尝试解析来自各种来源的 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&#039;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&#039;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。这是链接

4

1 回答 1

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";
}
于 2013-08-17T13:33:17.717 回答