我如何使用XPath和DOM来替换php中的节点/元素?
说我有以下的HTML
$html = '
<div class="website">
<div>
<div id="old_div">
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<div class="a class">
<p>some text</p>
<p>some text</p>
</div>
</div>
<div id="another_div"></div>
</div>
</div>
';
我想用以下代码替换#old_div
:
$replacement = '<div id="new_div">this is new</div>';
为了给出最终结果:
$html = '
<div class="website">
<div>
<div id="new_div">this is new</div>
<div id="another_div"></div>
</div>
</div>
';
有没有一个简单的剪切和粘贴功能,用PHP来做到这一点?
最后的工作代码感谢所有戈登的帮助:
<?php
$html = <<< HTML
<div class="website">
<div>
<div id="old_div">
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<div class="a class">
<p>some text</p>
<p>some text</p>
</div>
</div>
<div id="another_div"></div>
</div>
</div>
HTML;
$dom = new DOMDocument;
$dom->loadXml($html); // use loadHTML if it's invalid XHTML
//create replacement
$replacement = $dom->createDocumentFragment();
$replacement ->appendXML('<div id="new_div">this is new</div>');
//make replacement
$xp = new DOMXPath($dom);
$oldNode = $xp->query('//div[@id="old_div"]')->item(0);
$oldNode->parentNode->replaceChild($replacement , $oldNode);
//save html output
$new_html = $dom->saveXml($dom->documentElement);
echo $new_html;
?>
由于链接副本中的答案并不全面,我将举一个例子:
$dom = new DOMDocument;
$dom->loadXml($html); // use loadHTML if its invalid (X)HTML
// create the new element
$newNode = $dom->createElement('div', 'this is new');
$newNode->setAttribute('id', 'new_div');
// fetch and replace the old element
$oldNode = $dom->getElementById('old_div');
$oldNode->parentNode->replaceChild($newNode, $oldNode);
// print xml
echo $dom->saveXml($dom->documentElement);
从技术上讲,你不需要XPath。 但是,可能发生的情况是,对于未经过验证的文档(id属性在XML中是特殊的),您的libxml版本无法执行getElementById
。 在这种情况下,请将调用替换为getElementById
$xp = new DOMXPath($dom);
$oldNode = $xp->query('//div[@id="old_div"]')->item(0);
在键盘上演示
要创建一个带有子节点的$newNode
,而不必一个接一个地创建和附加元素,你可以这样做
$newNode = $dom->createDocumentFragment();
$newNode->appendXML('
<div id="new_div">
<p>some other text</p>
<p>some other text</p>
<p>some other text</p>
<p>some other text</p>
</div>
');
首先使用jquery hide()来隐藏特定的div,然后使用append来追加新的div
$('#div-id').remove();
$('$div-id').append(' <div id="new_div">this is new</div>');
链接地址: http://www.djcxy.com/p/49741.html
上一篇: How can I use XPath and DOM to replace a node/element in php?
下一篇: Can you make a jQuery call to WCF service using SOAP and WSHttpBinding?