要获取“url”属性,请使用->attribute()
syntax:
$ns_media = $news->children('http://search.yahoo.com/mrss/');
/* Echoes 'url' attribute: */
echo $ns_media->content->attributes()['url'];
// in php < 5.5: $attr = $ns_media->content->attributes(); echo $attr['url'];
/* Catches 'url' attribute: */
$url = $ns_media->content->attributes()['url']->__toString();
// in php < 5.5: $attr = $ns_media->content->attributes(); $url = $attr['url']->__toString();
命名空间说明:
The ->children()
参数不是 XML 的 URL,而是一个命名空间 URI.
XML 命名空间用于在 XML 文档中提供唯一命名的元素和属性:
<xxx> Standard XML tag
<yyy:zzz> Namespaced tag
└┬┘ └┬┘
│ └──── Element Name
└──────── Element Prefix (Namespace Identifier)
所以,就你而言,<media:content>
是命名空间“media”的“内容”元素。命名空间元素必须具有关联的命名空间 URI,作为父节点的属性,或者最常见的是根元素的属性:该属性具有以下形式xmlns:yyy="NamespaceURI"
(在你的情况下xmlns:media="http://search.yahoo.com/mrss/"
作为根节点的属性<rss>
).
最终,上述$news->children( 'http://search.yahoo.com/mrss/' )
意味着“检索所有子元素http://search.yahoo.com/mrss/作为命名空间 URI;另一种最容易理解的语法是:$news->children( 'media', True )
(True
意思是“被视为前缀”)。
返回示例中的代码,检索所有内容的通用语法第一项的有前缀的孩子media
is:
$xml = simplexml_load_file( 'http://rssfeeds.webmd.com/rss/rss.aspx?RSSSource=RSS_PUBLIC' );
$xml->channel->item[0]->children( 'http://search.yahoo.com/mrss/' );
或(相同的结果):
$xml = simplexml_load_file( 'http://rssfeeds.webmd.com/rss/rss.aspx?RSSSource=RSS_PUBLIC' );
$xml->channel->item[0]->children( 'media', True );
您的新代码:
如果你想展示<media:content url>
页面中每个元素的缩略图,按以下方式修改原始代码:
(...)
$pubDate = $xml->channel->item[$i]->pubDate;
$image = $xml->channel->item[$i]->children( 'media', True )->content->attributes()['url'];
// in php < 5.5:
// $attr = $xml->channel->item[$i]->children( 'media', True )->content->attributes();
// $image = $attr['url'];
$html .= "<a href='$link'><h3>$title</h3></a>";
$html .= "<img src='$image' alt='$title'>";
(...)