Working with DOM in PHP – Add elements to XML
It’s almost unavoidable in web programming to work with XML. We can retrieve an XML structure from string or a file. But, what if we want to change it, e.g. to add, remove, change elements or attributes or whatever. In that case DOM (Document Object Model) is used. What we do is, create document, load XML from any source, and do what you have to.
To generate a DOM, put this:
$doc = new DOMDocument('1.0','utf-8');
This will create XML root, like: <?xml version=”1.0″ encoding=”utf-8″?>. Let’s say you have a string $xmlstring and $element as mixed variable to represent a new element, so after we created a root, next is to load string in XML form:
$newEl = $doc->createElement("elementName",$element);
That’s it, you’ve added an element to the DOM. Now we can get final result by getting string from DOM:
There is one catch though… This will return string WITH root (<?xml … ?>l). I figured, like this string is 22 characters in length (if utf-8 is used), so this
$xml = substr($doc->saveXML(),22,strlen($doc->saveXML()));
will return the whole string without the stupid root at top ;)
Hope you found something useful in this post.
Share this story:
Leave a Reply