开发者

Error while using contains in XPath query

开发者 https://www.devze.com 2023-01-26 18:34 出处:网络
I\'m trying to parse the following URL: http://rss.cbc.ca/lineup/technology.xml My code is: $doc = new DOMDocument();

I'm trying to parse the following URL: http://rss.cbc.ca/lineup/technology.xml

My code is:

$doc = new DOMDocument();
$doc->load("http://rss.cbc.ca/lineup/technology.xml");

echo '<ul class="rss">';

$i = 0;

if( isset($_GET['filter']) ){
    $xpath = new DOMXPath($doc);
    $doc = $xpath->query("item/title[contains(.,'".$_GET['filter']."')] or item/description[contains(.,'".$_GET['filter']."')]");
    echo 开发者_开发技巧"<p>Filtering news items on '".$_GET['filter']."'</p>";

}


foreach ($doc->getElementsByTagName('item') as $node) {

    if($i % 2 == 0)
        $class = "even";
    else
        $class = "odd";
    echo '<li class="'.$class.'">';
    echo "<h1>".$node->getElementsByTagName('title')->item(0)->nodeValue."</h1>";
    echo "<p>".$node->getElementsByTagName('description')->item(0)->nodeValue."</p>";
    echo '<a href="'.$node->getElementsByTagName('link')->item(0)->nodeValue.'">Link to story</a>';
    echo "</li>";
    $i = $i + 1;
}

echo "<ul>";

The issue that I'm having is that if I specify a filter (through a URL var), when I do the foreach later down the page, I get an error:

Fatal error: Call to undefined method DOMNodeList::getElementsByTagName()


Your XPath expression is evaluated to a boolean data type (false, because your path is wrong)

If you want to select those item elements having title or description children containg some string, use:

/rss/channel/item[(title|description)[contains(.,'string')]]


First: $xpath->query returns a DOMNodeList which does not have a method getElementsByTagName.

Second: Your query returns the title element or the description and not the item.

Change it to //item[contains(title,'".$_GET['filter']."')]

0

精彩评论

暂无评论...
验证码 换一张
取 消