A quick and dirty intro to using PHP to manipulate XML. Very useful to know since there are probably situations where MySQL might be unavailable or just impractical and XML can make a great replacement, especially in small/light-weight applications.
The first place we start is by looking at PHP’s DOM extension; read through the Introduction and Installation/Configuration sections before continuing.
Now we’ll access the DOMDocument class. Starting out, this will probably be the class that gets used the most but as things progress, you’ll find yourself making use of the other classes available.
$xmldoc = new DOMDocument(); // create a new DOMDocument object.
Yep, it’s that simple. Now here comes the fun part. This scenario is going to assume that we’re just creating a new XML object.
$xmldoc->formatOutput = true; //Nicely formats output with indentation and extra space. $root = $xmldoc->createElement( 'xml' ); //create a root element for your XML output $xmldoc->appendChild( $root ); // Now, we're going to create a few child elements to go with it $child1 = $xmldoc->createElement( 'child_one', 'Child One' ); $root->appendChild( $child1 ); $child2 = $xmldoc->createElement( 'child_two', 'Child Two' ); $root->appendChild( $child2 ); echo $xmldoc->saveXML(); //output to screen...
Pretty simple and straightforward. Now, if we want to save to a file, we do this:
$xmldoc->save( 'my-xml-file.xml' );
If we want to open and write to a file:
$xmldoc = new DOMDocument(); // create a new DOMDocument object. $xmldoc->load( 'my-xml-file.xml' ); $xmldoc->formatOutput = true; $root = $xmldoc->documentElement; // Conviently allows direct access to the root element. $b = $xmldoc->createElement( 'another_one', 'another child' ); $root->appendChild( $b ); $xmldoc->save( 'my-xml-file.xml' );
Very quick and straightforward. I hope this helps anyone who was wondering how to use XML and PHP together.
For more information see:
- PHP Manual: XML Manipulation
- Kirupa.com: PHP and XML
- IBM.com: XML for PHP Developers, Part 1 (three-part series)
- DynamicDrive Forums: Read and Write XML with PHP (forum-post, this is what got me started)