xpath - 如何更改xpath返回的节点的值?

时间:2014-04-03 09:41:46

标签: php dom xpath

我有一系列需要从一段html中替换的ID。

$ids = array(
    '111' => '999', // I need to replace data-note 111 with 999
    '222' => '888' // same 222 needs to be replace with 888
);

$html = '<span data-note="111" data-type="comment">el </span> text <span data-note="222" data-type="comment">el </span>';
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DomXpath($dom);
$elements = $xpath->query("//span/@data-note");
foreach($elements as $element){
    echo $element->value . ' '; // echos the correct values
$element->value = 999; // here I want to change the value inside the $html file. how to do this
}

我的问题是如何用$ html变量中的数组替换它们?

1 个答案:

答案 0 :(得分:2)

你必须做两件事:

PHP默认添加html和body元素,因此循环遍历body标签的所有子节点以重建输出:

foreach($elements as $element){
    echo $element->value . ' '; // echos the correct values
$element->value = $ids[$element->value]; // Look up and change to new value
}
$html = '';
foreach($xpath->query('/html/body/* | /html/body/text()') as $element) {
  $html .= $element->C14N();
}
echo $html;

使用PHP 5.4+,您将能够使libxml 添加html和body元素:

$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED);
// [snip]
$html = $dom->C14N();
echo $html;