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>';
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);
}
来源:https://stackoverflow.com/questions/25565830/how-to-read-image-tag-from-rss-itunes