简体   繁体   English

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

[英]xpath - How to change the values of nodes returned by xpath?

I have an array of ids that need replacing from a piece of html. 我有一系列需要从一段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
}

My question is how to replace them with the values from the array in the $html variable? 我的问题是如何用$ html变量中的数组值替换它们?

You will have to do two things: 你将不得不做两件事:

  • Look up the new value instead of a constant 查找新值而不是常量
  • Use $dom->C14N() to extract the new HTML to a string, or $dom->C14N($uri) which directly saves it to a file. 使用$dom->C14N()将新HTML提取为字符串,或者$dom->C14N($uri)其直接保存到文件中。

PHP by default adds html and body elements, so loop over all child nodes of the body tag to reconstruct the output: 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;

Using PHP 5.4+, you will be able to make libxml not add html and body elements: 使用PHP 5.4+,您将能够使libxml 添加html和body元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM