user3072613
user3072613

Reputation: 363

convert string to domelement in php

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.

Upvotes: 7

Views: 11171

Answers (1)

Ralph Ritoch
Ralph Ritoch

Reputation: 3440

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

Upvotes: 10

Related Questions