$dom = new DOMDocument();
// 加载 HTML 字符串
// 注意:这里我们使用 loadHTML 而不是 load,因为 loadHTML 是用来加载 HTML 字符串的
libxml_use_internal_errors(true); // 忽略警告,如 "Tag html invalid"
$dom->loadHTML('<?xml encoding="UTF-8">' . $html); // 添加 XML 声明以修复可能的编码问题
//$dom->loadHTML($html);
$dom->formatOutput = true; // 使输出的 HTML 格式化
libxml_clear_errors(); // 清除错误
// 输出整个 DOM 树(可选)
// 递归函数来遍历DOM树并打印节点信息
function printNodeInfo($node, $indent = '') {
// 打印节点名称和属性值
//echo $indent . $node->nodeName . "\n";
if ($node->hasAttributes()){
foreach ($node->attributes as $attr) {
// echo $indent . ' ' . 'Attribute: ' . $attr->name . ' = ' . $attr->value . "\n";
//尝试修改当前数据内容
if($attr->name == 'name' and $attr->value == '搜索框'){
$node->setAttribute('placeholder', '哈哈哈');
// 获取父节点
$parentNode = $node->parentNode;
$parentNode->setAttribute('action', '新的父节点属性值');
}
}
}
// 如果节点有子节点,递归遍历它们
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType === XML_ELEMENT_NODE) {
printNodeInfo($childNode, $indent . ' '); // 增加缩进以表示层级关系
}
}
}
}
//从根节点开始打印
printNodeInfo($dom->documentElement);
$html = $dom->saveHTML();