Generating XML using PHP

Long back I was hunting the entire web for some tutorials for generating XML using PHP. To my surprise, there are only a handful of them, where half of them are not of any use. Since PHP Library is very large, finding the right library was also a vey dauntng task. I first encounted XMLWriter, but it echoed the generated XML right out on the page. It’s useless in case when you want to send the generated XML across a network over socket.

After googling, I found a library called DOMDocument which helped me a lot and cleared off all problems in matter of minutes. It looks similar to .NET’s XMLWriter library or maybe the way round.

To start with we create a new instance of XMLDocument using

$doc = new DOMDocument();

Now if you want to turn on the XML Formatting , you need this line

$doc->formatOutput = true;

Now if you want to create a new Node Element or Text Element, all of them have to be created from $doc using createElement and createTextNode methods of DOMDocument class. If you want to create a Node Element and attach it to its parent, then use this code

$operation = $doc->createElement("operation");

where operation string passed in createElement is the name of the XML Node.

TextNode are also a kind of Node and is represented by a node below its outer Element.

$type = $doc->createTextNode("kill");

You can use arrays to store data temporarily and use the foreach construct to fetch the key value pairs.

$student = array( "name" => "Mike Ross" , "age" => 25 ,
     "dob" => "1980-10-12" , "post" => "CEO");

foreach ( $student as $key => $value )


    // Your processing here


Now if you want to retrieve the data stored inthe $doc object, use the saveXML method to fetch th String


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s