使用命名空间解析php中的RSS / XML

时间:2013-01-17 16:37:58

标签: php xml parsing rss

我有一些看起来像这样的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:categorymedia:groupsomething:anything出现 - 他们只是被剥夺了。

如何解析此Feed而不会丢失它们?

1 个答案:

答案 0 :(得分:1)

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

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

输出:

  

大公司

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

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

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