How to read image tag from RSS itunes

青春壹個敷衍的年華 提交于 2019-12-01 06:06:41

问题


I try to read my iTunes RSS. I can read title, even itunes:subtitle but I have problems with the tag image.

FEED:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">

<channel>
<title>title of the podcast</title>  
<itunes:image href="http://www.MyWeb/myImg.png"/>
</channel>
</rss>

PHP:

$xml=("http://www.myWeb/rss.xml");
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

$channel=$xmlDoc->getElementsByTagName('channel')->item(0);

$channel_title = $channel->getElementsByTagName('title')//normal tag
->item(0)->childNodes->item(0)->nodeValue;

$channel_image = $channel->getElementsByTagName('image') //problem
->item(0)->childNodes->item(0)->nodeValue;

echo $channel_title . '<br>';
echo $channel_image . '<br>';

回答1:


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();
}



回答2:


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);
}


来源:https://stackoverflow.com/questions/25565830/how-to-read-image-tag-from-rss-itunes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!