Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to domelement in php

Tags:

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.

like image 987
user3072613 Avatar asked Dec 06 '13 19:12

user3072613


People also ask

How to convert string to DOM node in JavaScript?

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.

How to set the value of an element in domelement?

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.

How do I create a new element in a DOM document?

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().

How do I use the UTF-8 encoding in domelement?

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!


1 Answers

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;
   }
}
like image 129
Ralph Ritoch Avatar answered Oct 14 '22 09:10

Ralph Ritoch