How to build XML using PHP and SimpleXML

Php code tutorial

In this tutorial I will be demonstrating how to build XML using PHP and the SimpleXML extension.

On some very rare occasions you will be called upon to work with XML, you will either need to generate it or consume it. The SimpleXML php extension allows you to easily accomplish both of these actions.

You will not need to install the SimpleXML extension as it comes installed and enabled by default. If it is not available either contact your hosting provider and request it or change hosting providers cause they suck.

Firstly, we need to initialize the SimpleXML extension.

//Build XMl to post
$xml = new SimpleXMLElement('<xml/>');

Now we start adding in the Elements and Values that will be used to structure and build the XML.

//First element is movies
$output = $xml->addChild('movies');

//Child element called movie
$movie = $output->addChild('movie');

//now add in our first movie as a child element to movie, take note that the parent variable is used to add a child element to

$movie->addChild('name', 'The Matrix');
$movie->addChild('released', '1999');
$movie->addChild('description', 'Awesomeness with a cherry of awesomeness ontop.');

Now we output our XML.

//Define the document header as XML so it can output as XML
Header('Content-type: text/xml');

//Now spit out the xml
$xml->asXML();

The above code should output the below xml structure.

SimpleXML sample ouput

You can also save the output as an actual XML file by removing the header and saving the output to a variable, you can then write that to a document as below.

//Save the output to a variable
$content = $xml->asXML();

//now open a file to write to
$handle = fopen('movies.xml', "w");

//Write the contents to the file
fwrite($handle, $content);

//Close the file
fclose($handle);

The above should create a movies.xml file in the same directory as the script. If not then check your folder and file permissions, it might be that they are not set correctly.

One thing to always keep in mind, the PHP manual is your best friend. If you are experiencing any issues check the manual.

Hope this helps, Nathaniel.

Other Posts