/** * Creates a new document by deserializing a string into XML * * This is a static method so that you won't need to instantiate a class beforehand; * For example: * * $document = DOMDocumentSerialize::deserialize( '<a @href # : Click Here >' ); * * @param string $serialized_text A string containing previously serialized XML * @param string $root_node A DOMDocument may have only one root element, but the serialized * XML form allows multiple elements side-by-side. In the instance of * deserializing into a new document, a custom root node *must* be * created. You can provide the name of this root element, otherwise * it will be `<DOMDocumentSerialize />` * * @return DOMDocumentSerialize An instance of this class containing an XML document tree * @throws \InvalidArgumentException */ public static function deserialize($serialized_text, $root_node = 'DOMDocumentSerialize') { //basic validation. an empty `$serialized_text` is valid, # and an empty (though with root node) document will be returned if (!is_string($serialized_text)) { throw new \InvalidArgumentException('`$serialized_text` parameter must be a string'); } if (!is_string($root_node) || trim($root_node) === '') { throw new \InvalidArgumentException('`$root_node` parameter must be a non-empty string'); } //create a new, empty document to begin with $document = new DOMDocumentSerialize(); //XML documents *must* have only one root element, i.e. `<a>1</a><b>2</b>` would be invalid. //we provide our own so that [de]serialized strings do not have to worry about this $context_node = $document->appendChild($document->createElement(trim($root_node))); //any empty string *is* valid input; you might be feeding in strings from external content that you don't //control. The result will be an effectively empty document (bar the root element) if (empty($serialized_text = trim($serialized_text))) { return $document; } //begin our recursive descent into the source string $context_node->deserialize($serialized_text); return $document; }