0

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!

4

2 回答 2

1

在您的循环内将其更改为:

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

如果您想创建嵌套的 HTML 元素,您将通过DOMElement为每个孩子和父母创建新的并将每个孩子附加到其父母来从最后一个孩子开始。例如:

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

你可以把它放在你的循环中:

$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

是的,当您输出时,您应该使用$html->saveHTML().

希望这可以帮助。

于 2016-06-26T08:10:29.117 回答
0

在内容如下的标签中:<h2>Tom</h2>,TomnodeValue并且h2nodeName.

您不能写入nodeName. 要创建一个新节点,您必须使用它:

$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); 
}

如果你想附加嵌套标签,就像<p><h2>Title</h2></p>你会做的那样:

$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
于 2016-06-26T08:03:16.550 回答