3
  $dom= new DOMDocument('1.0', 'iso-8859-1');
  $dom->loadHTML(' <html><body> <strong>SECOND</strong> </body></html>');

  $path = new DOMXPath($dom);

  foreach($path->query('body') as $found){
      $found->nodeValue  = ' <strong>FIRST</strong> '.$found->nodeValue;
  }

var_dump($dom->saveHTML()); //It shows <strong> as "&lt;strong&gt;"

The "strong" tags in this example will be transformed in text. Actually I need to add a big HTML code there. And its not well formated, somethings will be fixed later.

How can I do this?

user534312
  • 91
  • 2
  • 7

4 Answers4

2

From this similar question: How to insert HTML to PHP DOMNode?

1) Create an helper function:

private static function __appendHTML($parent, $rawHtml) {
   $tmpDoc = new DOMDocument();
   $tmpDoc->loadHTML($rawHtml);
   foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
       $importedNode = $parent->ownerDocument->importNode($node, TRUE); 
       $parent->appendChild($importedNode);
   }
}

2) Use the helper to insert raw html into an element:

$elem = $domDocument->createElement('div');
appendHTML($elem, '<h1>Hello world</h1>');
Community
  • 1
  • 1
valentinarho
  • 121
  • 1
  • 5
  • Please flag as a duplicate rather than posting an answer that's just an link to another question on Stack Overflow. – ChrisF Sep 21 '15 at 16:15
1

Simply use createCDATASection function:$found->appendChild($dom->createCDATASection ( ' <strong>FIRST</strong> '.$found->nodeValue ));

antoniOS
  • 370
  • 2
  • 9
1

In order to add new parts of the XML, you'll need to create DOM nodes out of them somehow instead of using straight text.

You might try using DOMDocument Fragment: http://www.php.net/manual/en/domdocumentfragment.appendxml.php

Or, as it suggests on that page, create an additional DOMDocument object and loop through the nodes to add them to your original DOMDocument.

fredrover
  • 2,997
  • 2
  • 17
  • 24
0
$first = new DOMElement('strong', 'first');
$path  = new DOMXPath($dom);

foreach($path->query('body') as $found)
{
  $found->insertBefore($first);
}
ajreal
  • 46,720
  • 11
  • 89
  • 119