php dom 只编辑父元素,不编辑子元素

php dom only edit parent element and not child elements

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

$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>

通过设置 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>