Using SimpleXML to create an XML object from scratch Using SimpleXML to create an XML object from scratch xml xml

Using SimpleXML to create an XML object from scratch


Sure you can. Eg.

<?php$newsXML = new SimpleXMLElement("<news></news>");$newsXML->addAttribute('newsPagePrefix', 'value goes here');$newsIntro = $newsXML->addChild('content');$newsIntro->addAttribute('type', 'latest');Header('Content-type: text/xml');echo $newsXML->asXML();?>

Output

<?xml version="1.0"?><news newsPagePrefix="value goes here">    <content type="latest"/></news>

Have fun.


In PHP5, you should use the Document Object Model class instead.Example:

$domDoc = new DOMDocument;$rootElt = $domDoc->createElement('root');$rootNode = $domDoc->appendChild($rootElt);$subElt = $domDoc->createElement('foo');$attr = $domDoc->createAttribute('ah');$attrVal = $domDoc->createTextNode('OK');$attr->appendChild($attrVal);$subElt->appendChild($attr);$subNode = $rootNode->appendChild($subElt);$textNode = $domDoc->createTextNode('Wow, it works!');$subNode->appendChild($textNode);echo htmlentities($domDoc->saveXML());


Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();$w->openMemory();$w->startDocument('1.0','UTF-8');$w->startElement("root");    $w->writeAttribute("ah", "OK");    $w->text('Wow, it works!');$w->endElement();echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.