【问题标题】:Parsing RSS/XML in php with namespaces使用命名空间在 php 中解析 RSS/XML
【发布时间】:2013-01-17 16:37:57
【问题描述】:

我有一些看起来像这样的 RSS:

<item>
<guid isPermaLink="false">2284767032</guid>
<title>title goes here...</title>
<description> Description </description>
<author>author name</author>
<dcterms:valid>start=2012-09-28T17:06:00Z;scheme=W3C-DTF</dcterms:valid>
<media:category scheme="" label="">cat1</media:category>
<media:category scheme="" label="">cat2</media:category>
<media:category scheme="" label="">cat3</media:category>

<media:copyright>Big Company</media:copyright>
<media:keywords>some;keywords;</media:keywords>
<media:group>
<media:content bitrate="643.386" medium="video" duration="72.144" expression="full" fileSize="5802051" framerate="29.97" type="video/x-flv" height="360" url="..." width="640"/>
<media:content bitrate="1242.571" medium="video" duration="72.144" expression="full" fileSize="11205501" framerate="29.97" type="video/x-flv" height="480" url="..." width="854"/>
</media:group>
<link>a234dfasf4f</link>
<plmedia:defaultThumbnailUrl>
  http://url.jpg
</plmedia:defaultThumbnailUrl>
</item>

我使用下面的代码来解析它:

  $feed = simplexml_load_file('http://feedurl.com');
  echo "<pre>";
  print_r($feed);
  echo "</pre>";

问题是我得到了像 guid、title 和 description 这样的所有标签,但没有一个 media:category 或 media:group 或 something:anything 出现 - 它们只是被剥离了。

如何在不丢失它们的情况下解析此提要?

【问题讨论】:

    标签: php xml parsing rss


    【解决方案1】:

    您需要找到命名空间的定义位置,并找到命名空间映射到的字符串。例如,如果media 命名空间映射到http://example.com/something:

    echo (string)$feed->children('http://example.com/something')->copyright;
    

    输出:

    大公司

    print_r() 与 SimpleXML 的结果并不总是为您提供完整的结构,但元素在那里。

    要获取嵌套元素,请尝试以下操作:

    foreach($feed->children('http://example.com/something')->group->children('http://example.com/something')->content as $content)
    {
        echo (string)$content->attributes()->bitrate;
    }
    

    【讨论】:

    • 那会在 RSS 文档的标题中吗?
    • @Wes 是的,它通常是,例如:&lt;rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"&gt; 这是itunes 命名空间的定义,定义为http://www.itunes.com/dtds/podcast-1.0.dtd。
    • 好的,有没有办法将它们全部组合到大对象/数组中?
    • 这是有效的,但对于嵌套的我得到这个:wes.io/MFAk - 我如何获得这些信息?
    • 您可以手动将数据添加到一个大数组中,但我不这么认为。要获得嵌套的,我认为您必须再次致电children()。查看我的编辑。
    猜你喜欢
    • 2012-06-11
    • 2013-04-30
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2021-05-03
    • 2014-01-10
    相关资源
    最近更新 更多