Create DOMNode from HTML fragment string

How can I create DOMNode

from a string an HTML fragment, assuming of course the string contains one root node?

+3


source to share


1 answer


DOMDocumentFragments have loadXML () method

libxml_use_internal_errors(1);

$opts = array('http' => array('header' => 'Accept-Charset: ISO-8859-1, *;q=0'));
$context = stream_context_create($opts);
$html = file_get_contents( 'http://multiple.webcindario.com/wstest.php' , false , $context );

$html = html_entity_decode(htmlentities($html, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-1');
ob_clean();
$classname = "product";
$domdocument = new DOMDocument();
$domdocument->preserveWhiteSpace = true;
$domdocument->formatOutput       = false;
$domdocument->loadHTML($html);
$xpath = new DOMXPath($domdocument);
$found = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

$newHTML="<div class='foo bar'><p>This is <b>an <i>example</i></b> paragraph    <a href='#!'>#!</a></p></div>";
$newHTML = html_entity_decode(htmlentities($newHTML, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-1');

foreach($found as $oldnode){
   $frag = $domdocument->createDocumentFragment();
   $frag->appendXML($newHTML);
   $oldnode->appendChild($frag);
   $updatedHTML=$domdocument->saveHTML();
 }

      



ex: http://multiple.webcindario.com/addNodefromHTML.php

(adds example paragraph as chilNode to selected source nodes)

+1


source







All Articles