Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SimpleXML to create an XML object from scratch

Tags:

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 :-)

like image 712
dirtside Avatar asked Sep 27 '08 06:09

dirtside


People also ask

What is SimpleXML extension?

SimpleXML is an extension that allows us to easily manipulate and get XML data. SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout.

How do you read and write XML document with PHP?

Start with $videos = simplexml_load_file('videos. xml'); You can modify video object as described in SimpleXMLElement documentation, and then write it back to XML file using file_put_contents('videos. xml', $videos->asXML()); Don't worry, SimpleXMLElement is in each PHP by default.


1 Answers

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.

like image 80
DreamWerx Avatar answered Sep 26 '22 22:09

DreamWerx