Php DOM:设置nodeValue时,代码未格式化,而是显示文字HTML标记

问题描述:

I am trying to replace one of my div's content:

  $html = new DOMDocument();
    $html->loadHTML($content);

    $elements = $html->getElementsByTagName('div');
    foreach($elements as $element){
      if($element->getAttribute('name') == "left_0"){
       $element->nodeValue = "<h2>Title</h2>";
     }

echo $html-> saveHTML(); 

I get the following output in my index.php:

<h2>Title</h2>

I was looking for an answer, but cant find a way to fix it. Thanks!

我正在尝试替换我的div内容之一: p>

  $ html = new DOMDocument(); 
 $ html-&gt; loadHTML($ content); 
 
 $ elements = $ html-&gt; getElementsByTagName('div'); 
 foreach($ elements as $ element  ){
 if($ element-&gt; getAttribute('name')==“left_0”){
 $ element-&gt; nodeValue =“&lt; h2&gt; Title&lt; / h2&gt;”; 
} 
  
echo $ html-&gt;  saveHTML()方法;  
  code>  pre> 
 
 

我在index.php中得到以下输出: p>

 &lt; h2&gt; Title&lt; / h2&gt  ; 
  code>  pre> 
 
 

我一直在寻找答案,但无法找到解决问题的方法。 谢谢! p> div>

In a tag with content like: <h2>Tom</h2>, Tom is the nodeValue and h2 is the nodeName.

You cannot write to nodeName. To create a new node you will have to use this:

$html = new DOMDocument();
$html->loadHTML($content);

$elements = $html->getElementsByTagName('div');
foreach($elements as $element) {
  if ($element->getAttribute('name') == "left_0") {
    $newElement = $html->createElement('h2','Tom'); 
    $element->appendChild($newElement); 
}

If you want to append nested tags, like <p><h2>Title</h2></p> you would do:

$paragraph = $html->createElement('p');         // create outer <p> tag
$currentElement->appendChild($paragraph);       // attach it to parent element
$heading2 = $html->createElement('h2','Title'); // create inner <h2> tag
$paragraph->appendChild($heading2);             // attach that to the <p> tag

Inside your loop change it to:

foreach($elements as $element) {
    if ($element->getAttribute('name') == "left_0") {
        $element->nodeValue = null;// removing the text inside the parent element
        $h2 = new \DOMElement('h2', 'Title');// create a new h2 element
        $element->appendChild($h2);// appending the new h2 to the parent element
    }
}

If you would like to create nested HTML elements, you will be making your way up from the last child by creating new DOMElement for each child and parent and appending each child to its parent. For example:

<div><h2>H2<h2/></div>

You would put this inside your loop:

$parentDiv = new \DOMElement('div', null);// the outer div
$childH2 = new \DOMElement('h2', 'H2');// the inner h2 tag
$parentDiv->appendChild($childH2); // append the h2 to div
$element->appendChild($parentDiv); // append the div with its children to the element

And yeah when you are outputting you should use $html->saveHTML().

Hope this helps.