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.
The document.createRange ().createContextualFragment function is an awesome, sane method for converting strings to DOM nodes within JavaScript. Ditch your old shims and switch to this performant, simple API! Today we have a standard way for converting string to DOM with JavaScript: DOMParser.
The tag name of the element. The value of the element. By default, an empty element will be created. The value can also be set later with DOMElement::$nodeValue . The value is used verbatim except that the < and > entity references will escaped.
DOMDocument::createElement — Create new element node. public DOMDocument::createElement ( string $name string $value ] ) : DOMElement. This function creates a new instance of class DOMElement. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().
DOMElement implémente désormais DOMParentNode et DOMChildNode . L'extension DOM utilise l'encodage UTF-8. Utilisez mb_convert_encoding () , UConverter::transcode (), ou iconv () pour manipuler d'autres encodages. DOMElement::setIdAttributeNS — Déclare l'attribut spécifié par son nom local et son espace de nom URI à être de type ID Caveat!
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With