How to read image tag from RSS itunes

空扰寡人 提交于 2019-12-01 09:27:09

You could use SimpleXML. Because the image element has a namespace prefix (itunes), you have to use the children method to pass the namespace URL, then call the attributes method:

$feed = simplexml_load_file('http://www.myWeb/rss.xml');
foreach ($feed->channel as $channel) {
  $ns_itunes = $channel->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
  echo $ns_itunes->image->attributes();
}

The attribute xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" defines an alias/prefix itunes for the a namespace.

The DOM resolves that to the namespace prefix, so you can read the image node name as:

{http://www.itunes.com/dtds/podcast-1.0.dtd}:image

You're currently using the standard DOM function to fetch nodes. Here are namespace aware versions of them (suffix NS). But a better solution is Xpath. This is part of the DOM extension and allows you to use expression to fetch data from a DOM.

Create an DOMXPath instance for your DOM and fetch the title as string:

$xpath = new DOMXpath($xmlDoc);

echo $xpath->evaluate('string(/rss/channel/title)'), "\n";

To address nodes in a namespace you need to register your own prefix for it.

$xpath = new DOMXpath($xmlDoc);
$xpath->registerNamespace('it', 'http://www.itunes.com/dtds/podcast-1.0.dtd');

echo $xpath->evaluate('string(/rss/channel/it:image/@href)');

Here can be several items so fetch and iterate them, use the returned node as the context argument in evaluate to get details.

foreach ($xpath->evaluate('/rss/channel/item') as $item) {
  echo $xpath->evaluate('string(enclosure/@url)', $item);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!