Creating XML files with PHP

Creating XML files with PHP using SimpleXML is really easy, and elegant.

To create a SimpleXML object from a string, I use the following code.

$xml = simplexml_load_string("<?xml version='1.0'?>\n<phpsysinfo></phpsysinfo>");

From there it's really easy to expand.


$xml = simplexml_load_string("<?xml version='1.0'?>\n<phpsysinfo></phpsysinfo>");
$generation = $xml->addChild('Generation');
$generation->addAttribute('version', PSI_VERSION);
$generation->addAttribute('timestamp', time());

This code will create something like this:


<phpsysinfo>
<Generation version="2.5.4-dev" timestamp="1185620717"/>
</phpsysinfo>

We can also add child elements.

$vitals = $xml->addChild('Vitals');
$vitals->addChild('Hostname', 'hostname');

This will return something like this:

<phpsysinfo>
<Generation version="2.5.4-dev" timestamp="1185620717"/>
<Vitals>
<Hostname>hostname</Hostname>
</Vitals>
</phpsysinfo>

For more information about the SimpleXML functions, have a look in the PHP manual.

PLease help with SimpleXML

Hi, I am new and learning. What I am trying to do is create and save a playlist.xml file. How do I go about doing this?

Submitted by Matt (not verified) on Thu, 12/06/2007 - 01:17.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><pre><blockquote>
  • Lines and paragraphs break automatically.
  • Insert Flickr images: [flickr-photo:id=230452326,size=s] or [flickr-photoset:id=72157594262419167,size=m].

More information about formatting options