在通过DOMNodes循环中执行XPath查询时始终获取相同的节点

I don't know why the following script doesn't work !
The $_node returned within the loop is always the first child node of my root content, whereas it should be the first, the second, etc... WHY ?

<?php
// utility function
function saveNodeAsHTML($node)
{
    $dom  = new DOMDocument('1.0');
    $node = $dom->importNode($node, true);
    $dom->appendChild($node);
    return $dom->saveHTML();
}

//  root content
$content = '<table><tbody><tr><td class="item"><span>cell1</span></td><td class="item"><span>cell2</span></td></tr></tbody></table>';
echo 'XML content : ' . htmlspecialchars($content);
$dom                     = new DOMDocument();
$dom->loadHTML( $content );
$xpath = new DOMXPath( $dom );
// XPath to get all td.item nodes
$query = "//td[contains(concat(' ', @class, ' '), ' item ')]";
$nodes = $xpath->query( $query );
echo '<br/><br/>LOOP START<br/>';
// looping through td.item nodes
foreach ( $nodes as $node ) {
    echo '<br/><br/>node being parsed : ' . htmlspecialchars(saveNodeAsHTML($node));
    // looking for the span tag inside the $node context
    $_query = "//span";
    $_nodes = $xpath->query( $_query, $node );
    $_node  = $_nodes->item( 0 );
    // $_node is alwayd the first item of the loop !!!
    echo '<br/>--node value : ' . saveNodeAsHTML($_node);
}
echo '<br/><br/>LOOP END<br/>';
?>

This script will output :

XML content : <table><tbody><tr><td class="item"><span>cell1</span></td><td class="item"><span>cell2</span></td></tr></tbody></table>

LOOP START

node being parsed : <td class="item"><span>cell1</span></td> 
--node value : cell1 

node being parsed : <td class="item"><span>cell2</span></td> 
--node value : cell1

LOOP END
查看全部
doushangxianq07480
doushangxianq07480
2015/06/17 20:31
  • xpath
  • php
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复