There are two common ways to do this.
DOMDocument
DOM XML was deprecated in favor of this. It follows the W3C specification so you have typical DOM methods such as getElementsByTagName
, getElementById
, appendChild
, removeChild
, etc. It also uses appropriate classes such as DOMElement
, DOMNode
and DOMNodeList
.
$doc = new DOMDocument('1.0','utf-8');
$root = $doc->appendChild($doc->createElement('markers'));
// output
echo $doc->saveXML();
If you know already how to traverse the DOM in Javascript you pretty much already know how to do it in PHP using DOMDocument and other related classes.
I don't know why Shankar's answer was downvoted unless there are people who favor the next method.
SimpleXML
SimpleXML attempts to live up to its name by using only two classes and using a parent-child structure to traverse the document.
$doc = new SimpleXMLElement('<markers/>');
// output
echo $doc->asXML();
An element in itself evaluates to its contents if it's treated as a string, and attributes can be accessed as you would access elements of an associative array.
$marker = $doc->addChild('marker');
$marker->addAttribute('color','red');
You can also do this if you don't really need to hang onto the reference to the element. You can't add multiple attributes using this method, however, so you'd still need the previous to add new attributes without traversing the whole document.
$doc->addChild('marker')->addAttribute('color','red');
Access your elements and attributes like so:
// red
echo $doc->marker[0]['color'];
To set the element value just set it.
$doc->marker[0] = 'Text Value';
// Text Value
echo $doc->marker[0];