convert string to domelement in php

php

Solution

Unless you want to write your own HTML parser you will need to use a DOMDocument to create DOMElements.

class MyApp {
   static function createElementFromHTML($doc,$str) {
       $d = new DOMDocument();
       $d->loadHTML($str);
       return $doc->importNode($d->documentElement,true);
   }
}

The problem with this method is shown in the following string

$str = "<div>1</div><div>2</div>";

This obviously doesn't have a single parent. Instead you should be ready to handle an array of DOMNode's

class MyApp {
   static function createNodesFromHTML($doc,$str) {
       $nodes = array();
       $d = new DOMDocument();
       $d->loadHTML("<html>{$str}</html>");
       $child = $d->documentElement->firstChild;
       while($child) {
           $nodes[] = $doc->importNode($child,true);
           $child = $child->nextSibling;
       }
       return $nodes;
   }
}

Problem

Is there any way to convert string to a DOMElement in php (not a DOMDocument) such that I can import it into a DOMDocumment? For example have the HTML string: ``` <div><div>Add Example</div><div>View more examples</div></div> ``` I would like to have it as though I used DOMDocument::createElement to create it. Then I would like to append it to a child of a DOMDocumment.

Original source