为什么不通过xpath php

时间:2018-12-17 19:47:55

标签: php xpath

为什么不通过xpath php显示html属性

<?php
$content = '<div class="keep-me">Keep this div</div><div class="remove-me" id="test">Remove this div</div>';
$badClasses = array('');

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($content);
libxml_clear_errors();
$xPath = new DOMXpath($dom);

foreach($badClasses as $badClass){
$domNodeList = $xPath->query('//div[@class="remove-me"]/@id');

$domElemsToRemove = ''; // container of deleted elements
foreach ( $domNodeList as $domElement ) {
    $domElemsToRemove .= $dom->saveHTML($domElement); // concat them
    $domElement->parentNode->removeChild($domElement); // then remove
}

}

$content = $dom->saveHTML();
echo htmlentities($domElemsToRemove);
?>
  

Works-// div [@ class =“ remove-me”]或// div [@ class =“ remove-me”] / text()

     

不起作用-// div [@ class =“ remove-me”] / @ id

也许有一种简单的方法

2 个答案:

答案 0 :(得分:0)

XPath //div[@class="remove-me"]/@id是正确的,但是您只需要循环返回的元素并将nodeValue添加到匹配ID的列表中即可。

$xPath = new DOMXpath($dom);

$domNodeList = $xPath->query('//div[@class="remove-me"]/@id');

$ids = []; // container of deleted elements
foreach ( $domNodeList as $domElement ) {
    $ids[] = $domElement->nodeValue;
}

print_r($ids);

答案 1 :(得分:0)

如果目的是像我解释问题一样获取类"remove-me"的任何元素的ID,那么也许您可以尝试这样-未经测试的顺便说一句...

....之前的其他代码

$xp=new DOMXpath( $dom );
$col= $xp->query( '*[@class="remove-me"]' );
if( $col->length > 0 ){
    foreach($col as $node){
        $id=$node->hasAttribute('id') ? $node->getAttribute('id') : 'banana';
        echo $id;
    }
}

但是,查看问题代码表明您希望删除节点-在这种情况下,构建节点数组(nodelist)并从头到尾遍历它-即:向后...