php - 为什么不通过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
也许有更简单的方法
解决方案
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);
推荐阅读
- c - 每次我尝试使用`clang -Weverything`进行编译时,都会收到警告“包含位置'/usr/local/include'对于交叉编译不安全”
- c# - 母版页中的下拉列表未返回由内容页设置的默认值
- docker - chroot 中的 Kubernetes 服务发现
- php - 使用 PHP 从 API 响应中访问值时遇到问题
- r - 有条件地对数据帧的每一行进行计数
- python - Apache Spark / PySpark,为动态键定义自定义 JSON 模式
- flutter - Flutter 中的传入约束是什么意思?
- swift - 滑块移动时删除注释 - 迅速
- r - 如何使用 R 抓取此表中的信息?
- zsh - 引用字符串以在命令行中使用