using simplexml to create an xml object from scratch

using simplexml to create an xml object from scratch  using -'php,xml,simplexml'

Is it possible to use PHP's SimpleXML functions to create an XML object from scratch?  Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?

I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.

I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)

asked Sep 16, 2015 by ajit.chavhan
0 votes

3 Answers

0 votes

Sure you can. Eg.

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



Have fun.

answered Sep 16, 2015 by vijaygupta1980
0 votes

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');
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');

echo htmlentities($domDoc->saveXML());
answered Sep 16, 2015 by jekbishnoi
0 votes

Please see my answer here. As 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->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
echo htmlentities($w->outputMemory(true));

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

answered Sep 16, 2015 by ashishshukla