简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM