首页 > 解决方案 > 为什么不通过xpath php显示属性html

问题描述

为什么不通过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);
?>

作品 - //div[@class="remove-me"] 或 //div[@class="remove-me"]/text()

不工作 - //div[@class="remove-me"]/@id

也许有更简单的方法

标签: phpxpath

解决方案


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);

推荐阅读