Create new XML file and write data to it? Create new XML file and write data to it? xml xml

Create new XML file and write data to it?


DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();$xml_album = $xml->createElement("Album");$xml_track = $xml->createElement("Track");$xml_album->appendChild( $xml_track );$xml->appendChild( $xml_album );$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();$xml->load('/tmp/test.xml');$nodes = $xml->getElementsByTagName('Album') ;if ($nodes->length > 0) {   //insert some stuff using appendChild()}//re-save$xml->save("/tmp/test.xml");


PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php    $doc = new DOMDocument( );    $ele = $doc->createElement( 'Root' );    $ele->nodeValue = 'Hello XML World';    $doc->appendChild( $ele );    $doc->save('MyXmlFile.xml');?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.


With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();$doc->add('Album', true)        ->add('Track', 'Track Title');$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');$doc->query('//Track')        ->attr('id', 123);

https://github.com/servo-php/fluidxml