如何遍历从 XPath 部分匹配创建的数组以显示 XML 元素

How to loop through Arrays created from XPath partial match to display the XML elements

我已经为此工作了一段时间,现在我完全陷入困境,我不确定我是否以正确的方式进行。

我的网站上显示了一个 RSS 提要。我创建了一个搜索框,我要求它与 XML 的 title/description 部分匹配。

  <?php
    $xml = <<<XML
    XML;
    $sxe = simplexml_load_file('http://www.music-news.com/rss/news.asp');
    $searchKeyword = $_POST["SearchBox"];
    $area = $sxe->xpath("//item[contains(title,'".$searchKeyword."')]");
    print_r($area);
   ?> 

当从搜索框的提交按钮调用此代码时,将转至仅显示关注的页面

Array ( [0] => SimpleXMLElement Object ( [title] => SimpleXMLElement Object ( ) [description] => SimpleXMLElement Object ( ) [link] => SimpleXMLElement Object ( ) [pubDate] => Mon, 27 Apr 2015 10:01:00 GMT [guid] => SimpleXMLElement Object ( ) [author] => SimpleXMLElement Object ( ) ) )

它正在 RSS 提要中恢复正确的记录(可以从发布日期确定)。但是我正在尝试获取它,以便搜索结果显示为网站上显示的原始 RSS 提要。初始 RSS 提要的代码如下

<?php

$rss = simplexml_load_file('http://www.music-news.com/rss/news.asp');

foreach ($rss->channel->item as $item) 
{
echo "<h2>" .$item->title . "</h2>";
echo "<p>" . $item->pubDate . "</p>";
echo "<p>" . $item->description .  "</p>";
echo '<p><a href="'. $item->link .'">' .ReadMore. "</a><p>";
} 
?>

如有任何帮助,我们将不胜感激

提前致谢

$area 应该是零到多个 simplexml 元素的数组,所以使用:

foreach($area as $item) {
    echo "<h2>" .$item->title . "</h2>";
    echo "<p>" . $item->pubDate . "</p>";
    // and so on
} 

查看工作示例:https://eval.in/319904

顺便说一句,您应该清理 $searchKeyword 以防止任何类型的有害输入,请参阅 Cleaning/sanitizing xpath attributes,特别是评分最高的答案的最后一段是关于使用 PHP 进行清理的。