我有一个 id 数组,需要从一段 html 中替换。
$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 变量中数组中的值替换它们?
您必须做两件事:
- 查找新值而不是常量
- 使用
$dom->C14N()
将新 HTML 提取为字符串,或将其直接保存到文件中的$dom->C14N($uri)
。
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;