[英]How to get iTunes-specific child nodes of RSS feeds?
I'm trying to process an RSS feed using PHP and there are some tags such as 'itunes:image'
which I need to process.我正在尝试使用 PHP 处理RSS 提要,并且有一些我需要处理的标签,例如'itunes:image'
。 The code I'm using is below and for some reason these elements are not returning any value.我正在使用的代码如下,出于某种原因,这些元素没有返回任何值。 The output is length is 0. output 的长度为 0。
How can I read these tags and get their attributes?我如何读取这些标签并获取它们的属性?
$f = $_REQUEST['feed'];
$feed = new DOMDocument();
$feed->load($f);
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
foreach($items as $key => $item)
{
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->textContent; // textContent
$arrt = $item->getElementsByTagName('itunes:image');
print_r($arrt);
}
getElementsByTagName
is specified by DOM, and PHP is just following that. getElementsByTagName
由DOM指定,PHP紧随其后。 It doesn't consider namespaces. 它不考虑名称空间。 Instead, use getElementsByTagNameNS
, which requires the full namespace URI (not the prefix). 而是使用getElementsByTagNameNS
,它需要完整的名称空间URI(而不是前缀)。 This appears to be http://www.itunes.com/dtds/podcast-1.0.dtd
*. 这似乎是 http://www.itunes.com/dtds/podcast-1.0.dtd
*。 So: 所以:
$img = $item->getElementsByTagNameNS('http://www.itunes.com/dtds/podcast-1.0.dtd', 'image');
// Set preemptive fallback, then set value if check passes
urlImage = '';
if ($img) {
$urlImage = $img->getAttribute('href');
}
Or put the namespace in a constant. 或将名称空间放在常量中。
You might be able to get away with simply removing the prefix and getting all image
tags of any namespace with getElementsByTagName
. 您可以通过简单地删除前缀并使用getElementsByTagName
获取任何名称空间的所有image
标签来摆脱getElementsByTagName
。
Make sure to check whether a given item has an itunes:image
element at all (example now given); 确保检查给定项目是否完全具有itunes:image
元素(现在给出示例); in the example podcast, some don't, and I suspect that was also giving you trouble. 在示例播客中,有些没有,我怀疑那也会给您带来麻烦。 (If there's no href
attribute, getAttribute
will return either null
or an empty string per the DOM spec without erroring out.) (如果没有href
属性,则getAttribute
将根据DOM规范返回null
或空字符串,而不会出错。)
* In case you're wondering, there is no actual DTD file hosted at that location, and there hasn't been for about ten years. * 如果您想知道,该位置没有托管任何实际的DTD文件,而且已经有十年了。
<?php
$rss_feed = simplexml_load_file("url link");
if(!empty($rss_feed)) {
$i=0;
foreach ($rss_feed->channel->item as $feed_item) {
?>
<?php echo $rss_feed->children('itunes', true)->image->attributes()->href;?>
<?php
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.