[英]PHP & XML: Can xpath include namespaces in the results, not just on the search?
我有一个包含名称空间的RSS feed。 我需要在结果中显示名称空间信息以及常规节点。 我正在尝试xpath,但现在遇到了麻烦,似乎找不到能满足我需要的答案(或者至少我理解的答案-他们可能正在回答我的问题,但我不明白。)
这是我的RSS feed(进行一些编辑以删除多余的节点):
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<item>
<title>...</title>
<link>...</link>
<description>...</description>
<author>...</author>
<pubDate>05/14/2008</pubDate>
<media:content url="http://www.url.com">
<media:title>...</media:title>
</media:content>
</item>
<item>
<title>...</title>
<link>...</link>
<description>...</description>
<author>...</author>
<pubDate>06/17/2008</pubDate>
<media:content url="http://www.url.com">
<media:title>...</media:title>
</media:content>
</item>
</channel>
到目前为止的代码如下:
if (file_exists($filePath)) {
$items = simplexml_load_file($filePath);
$items->registerXPathNamespace("media","http://search.yahoo.com/mrss/");
$items = $items->xpath('//item');
usort($items, "toSort"); // sorts using an included function
// output the file
foreach($items as $item) {
echo '<div class="grayBx">';
echo $item->content->attributes()->url;
echo '<h2>' . $item->title . '</h2>';
echo '<p>' . $item->description . '</p>';
echo '<p><a href="' . $item->link . '">read more >></a></p>';
echo '</div>';
echo '<div class="clearBoth"> </div>';
}
}
就目前而言,据我所知,xpath将simplexml_load_file更改为数组类型,并且在大多数情况下还可以更轻松/更快地进行搜索。 问题是,当我使用xPath时,它会剥离介质:结果中没有名称空间,而介质结果是存储缩略图的位置,我需要在页面上显示图像。
我被卡住了,我不确定这是否是正确的道路。 有人可以帮忙吗?
您需要使用SimpleXMLElement::children
获取命名空间元素,这允许您传递命名空间:
foreach($items as $item) {
// media is an array with the media:* children of the item (ie media:content)
$media = $item->children('http://search.yahoo.com/mrss/');
echo '<div class="grayBx">';
echo $media[0]->attributes()->url; // media:content->attrinutes()->url
echo '<h2>' . $item->title . '</h2>';
echo '<p>' . $item->description . '</p>';
echo '<p><a href="' . $item->link . '">read more >></a></p>';
echo '</div>';
echo '<div class="clearBoth"> </div>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.