php dom只编辑父元素而不是子元素

时间:2015-03-13 23:10:19

标签: php dom element

我试图仅编辑父元素(例如hold1)的nodevalue而不是子元素。下面的代码成功地让我编辑子元素,但是当我编辑父元素时,它会完全删除子元素。请帮忙。

$file = 'home/aa.php';
$doc = new DOMdocument();
$doc = loadHTMLFile($file);
$element = $doc->getElementById('hold1');
$element->nodeValue= "THIS IS SPARTA";
$myfile = fopen($file,'w+'); // i have tried c, c+, a+, r+ , none helps
$html = fwrite($myfile,$doc->saveHTML());

//aa.php
<div id = "hold1"> 
<div id = "hold2"> Tom is Cruise </div>
<div id = "hold3"> Ben Stiller parody </div>
</div>

1 个答案:

答案 0 :(得分:1)

通过设置nodeValue,您可以设置元素的完整主体。您需要明确要求新文本节点的位置。例如:

$element = $doc->getElementById('hold1');
$element->insertBefore($doc->createTextNode("THIS IS SPARTA"), $element->firstChild);

将其放在开头

<div id="hold1">THIS IS SPARTA
<div id="hold2"> Tom is Cruise </div>
<div id="hold3"> Ben Stiller parody </div>
</div>