【问题标题】:Reading JSON in this scenario?在这种情况下读取 JSON?
【发布时间】:2013-08-17 13:11:03
【问题描述】:

我正在尝试解析来自各种来源的 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。这是 link

【问题讨论】:

  • 我没有看到任何 JSON,只有 XML 可用。
  • @RajatSaxena 你能展示(jsfiddle?)你是如何使用 YQL/json 提要的吗?
  • 我只从 PHP 解析它,我没有使用 javascript。另外,我只粘贴了我在我的问题中使用的 PHP 代码。

标签: php json yql


【解决方案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";
}

【讨论】:

  • 谢谢,帮了大忙
  • @RajatSaxena haha​​ :P 发布我的坏消息已成为一种习惯。顺便说一句,您是否有不想直接读取 XML 的原因?
  • 不,我似乎喜欢 JSON。
  • @RajatSaxena 如果您感兴趣,我在底部发布了一个如何使用 SimpleXML 阅读它的简单示例;)
  • 你知道php中如何判断字符串是text还是html吗?
猜你喜欢
  • 1970-01-01
  • 2022-10-19
  • 2021-08-24
  • 1970-01-01
  • 2021-12-11
  • 2018-06-24
  • 2013-04-23
  • 2013-05-19
  • 2015-06-16
相关资源
最近更新 更多