Creating XML Documents in PHP

There's lots of reasons why you'd want to make XML documents using PHP. Maybe you're writing your own RSS feed or implementing a REST service. Whatever the reason, this tutorial will introduce you to the DOMDocument object and how to use it to create dynamic XML documents.

Before we start creating some actual XML, we're going to need something to make it from. I'm going to start by declaring a class that will hold some information about recent tutorials here at Switch On The Code. We'll take a collection of these objects and produce the same XML that is parsed by jQuery in a previous tutorial.

class Tutorial
{
public $author;
public $title;
public $date;
public $categories;

function __construct(
$author, $title, $date, $categories)
{
$this->author = $author;
$this->title = $title;
$this->date = $date;
$this->categories = $categories;
}
}

Here we have a very simple PHP object that holds various pieces of information about a tutorial - author, title, publish date, and categories. Let's populate an array of four of these objects that we'll then convert to XML.

$tutorials = array(
new Tutorial(
"The Reddest",
"Silverlight and the Netflix API",
"1/13/2009",
array(
"Tutorials",
"Silverlight 2.0",
"Silverlight",
"C#",
"XAML"
)
),

new Tutorial(
"The Hairiest",
"Cake PHP 4 - Saving and Validating Data",
"1/12/2009",
array(
"Tutorials",
"CakePHP",
"PHP"
)
),

new Tutorial(
"The Tallest",
"Silverlight 2 - Using initParams",
"1/6/2009",
array(
"Tutorials",
"Silverlight 2.0",
"Silverlight",
"C#",
"HTML"
)
),

new Tutorial(
"The Fattest",
"Controlling iTunes with AutoHotkey",
"12/12/2008",
array(
"Tutorials",
"AutoHotkey",
)
)
);

Now we're into the meat of the tutorial - actually building some XML.

header("Content-Type: text/plain");

//create the xml document
$xmlDoc = new DOMDocument();

//create the root element
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("RecentTutorials"));

//make the output pretty
$xmlDoc->formatOutput = true;

echo $xmlDoc->saveXML();

The first line just tells browsers that I'm not returning HTML, I'm simply returning plain text. This prevents them from trying to render our XML as HTML, which usually doesn't work and gives you a blank screen. I then create an instance of DOMDocument. The constructor takes in an optional version and encoding, but it defaults to "1.0", which works for me. Next I create the root node, which in my case is RecentTutorials. I do this by creating an element using DOMDocument's createElement function and append it as a child to the XML document. Now I simply tell the DOMDocument to format the output, which makes it pretty, and echo it to the display. If we run this script right now, we'd end up with this:

<?xml version="1.0"?>
<RecentTutorials/>

Now let's start populating our XML with some information about tutorials. We'll start by simply creating a Tutorial tag and displaying the author as an attribute and the title and date as child elements.

foreach($tutorials as $tut)
{
//create a tutorial element
$tutTag = $root->appendChild(
$xmlDoc->createElement("Tutorial"));

//create the author attribute
$tutTag->appendChild(
$xmlDoc->createAttribute("author"))->appendChild(
$xmlDoc->createTextNode($tut->author));

//create the title element
$tutTag->appendChild(
$xmlDoc->createElement("Title", $tut->title));

//create the date element
$tutTag->appendChild(
$xmlDoc->createElement("Date", $tut->date));
}

I first create a tag for the tutorial the same way as I made the root tag, except now I added it as a child to the root element instead of the XML document. Unfortunately, unlike createElement, createAttribute doesn't have the ability to take the value in the constructor. This means we have to use some very verbose syntax to get an attribute added to an element. First we call createAttribute and pass it the name we want, then we have to append the value of the attribute as a child by calling createTextNode and passing it the value. Once we have the attribute created, we simply append it as a child to the tutorial tag. Lastly we add elements for the title and date by calling createElement and passing in the names and values. Now we've got something that looks like this:

<?xml version="1.0"?>
<RecentTutorials>
<Tutorial author="The Reddest">
<Title>Silverlight and the Netflix API</Title>
<Date>1/13/2009</Date>
</Tutorial>
<Tutorial author="The Hairiest">
<Title>Cake PHP 4 - Saving and Validating Data</Title>
<Date>1/12/2009</Date>
</Tutorial>
<Tutorial author="The Tallest">
<Title>Silverlight 2 - Using initParams</Title>
<Date>1/6/2009</Date>
</Tutorial>
<Tutorial author="The Fattest">
<Title>Controlling iTunes with AutoHotkey</Title>
<Date>12/12/2008</Date>
</Tutorial>
</RecentTutorials>

All that's left to add now are the categories. We've actually already seen everything we'll need to display them, so it's just a matter of looping through them and adding elements to the document.

//create the categories element
$catTag = $tutTag->appendChild(
$xmlDoc->createElement("Categories"));

//create a category element for each category in the array
foreach($tut->categories as $cat)
{
$catTag->appendChild(
$xmlDoc->createElement("Category", $cat));
}

And there you have it. Now we've got our complete XML document.

<?xml version="1.0"?>
<RecentTutorials>
<Tutorial author="The Reddest">
<Title>Silverlight and the Netflix API</Title>
<Date>1/13/2009</Date>
<Categories>
<Category>Tutorials</Category>
<Category>Silverlight 2.0</Category>
<Category>Silverlight</Category>
<Category>C#</Category>
<Category>XAML</Category>
</Categories>
</Tutorial>
<Tutorial author="The Hairiest">
<Title>Cake PHP 4 - Saving and Validating Data</Title>
<Date>1/12/2009</Date>
<Categories>
<Category>Tutorials</Category>
<Category>CakePHP</Category>
<Category>PHP</Category>
</Categories>
</Tutorial>
<Tutorial author="The Tallest">
<Title>Silverlight 2 - Using initParams</Title>
<Date>1/6/2009</Date>
<Categories>
<Category>Tutorials</Category>
<Category>Silverlight 2.0</Category>
<Category>Silverlight</Category>
<Category>C#</Category>
<Category>HTML</Category>
</Categories>
</Tutorial>
<Tutorial author="The Fattest">
<Title>Controlling iTunes with AutoHotkey</Title>
<Date>12/12/2008</Date>
<Categories>
<Category>Tutorials</Category>
<Category>AutoHotkey</Category>
</Categories>
</Tutorial>
</RecentTutorials>

And just so you can see everything in one place, here is the final content of the PHP script:

class Tutorial
{
public $author;
public $title;
public $date;
public $categories;

function __construct(
$author, $title, $date, $categories)
{
$this->author = $author;
$this->title = $title;
$this->date = $date;
$this->categories = $categories;
}
}

//make some tutorial objects
$tutorials = array(
new Tutorial(
"The Reddest",
"Silverlight and the Netflix API",
"1/13/2009",
array(
"Tutorials",
"Silverlight 2.0",
"Silverlight",
"C#",
"XAML"
)
),

new Tutorial(
"The Hairiest",
"Cake PHP 4 - Saving and Validating Data",
"1/12/2009",
array(
"Tutorials",
"CakePHP",
"PHP"
)
),

new Tutorial(
"The Tallest",
"Silverlight 2 - Using initParams",
"1/6/2009",
array(
"Tutorials",
"Silverlight 2.0",
"Silverlight",
"C#",
"HTML"
)
),

new Tutorial(
"The Fattest",
"Controlling iTunes with AutoHotkey",
"12/12/2008",
array(
"Tutorials",
"AutoHotkey",
)
)
);

//create the xml document
$xmlDoc = new DOMDocument();

//create the root element
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("RecentTutorials"));


foreach($tutorials as $tut)
{
//create a tutorial element
$tutTag = $root->appendChild(
$xmlDoc->createElement("Tutorial"));

//create the author attribute
$tutTag->appendChild(
$xmlDoc->createAttribute("author"))->appendChild(
$xmlDoc->createTextNode($tut->author));

//create the title element
$tutTag->appendChild(
$xmlDoc->createElement("Title", $tut->title));

//create the date element
$tutTag->appendChild(
$xmlDoc->createElement("Date", $tut->date));

//create the categories element
$catTag = $tutTag->appendChild(
$xmlDoc->createElement("Categories"));

//create a category element for each category in the array
foreach($tut->categories as $cat)
{
$catTag->appendChild(
$xmlDoc->createElement("Category", $cat));
}
}

header("Content-Type: text/plain");

//make the output pretty
$xmlDoc->formatOutput = true;

echo $xmlDoc->saveXML();

Overall, I find the process of creating XML documents in PHP a little verbose, especially when compared to using .NET's XDocument object. That aside, it's still very simple, powerful, and definitely gets the job done.

References
0
Average: 4.5 (2 votes)

First of all we are three guys who work full time but in our spare time run our fledgling company. We enjoy all types of programming with emphasis on web development and .Net, along with trying to keep up this blog. Charlie is a DZone MVB and is not an employee of DZone and has posted 3 posts at DZone.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

deewang replied on Mon, 2009/06/22 - 5:19am

I don't get the idea why they start these kind of trial when the criminal are old. Really funny. Perhaps this more personal form of accountability will deter future actors where the fear of international condemnation has not.


---------------------------------------------------------------------
Ed Hardy Clothing | Cheap Ed Hardy | Funny T-Shirts | Ed Hardy UK | Ed Hardy Clothing

luckey replied on Tue, 2009/06/30 - 12:03am

Links of London are very famous for offering many styles of bracelets with top quality and hot price. Tiffanysjewellery is the online shopping for Tiffany & Co Bracelets and Bangles Jewelry.In tiffanys jewellery online necklace store, You can chase after every kind of Tiffany Jewellery you want, such as Silver Necklaces, Heart Necklaces, Beaded necklaces and Chain necklaces. The necklace styles are from classic to modern, and there must be one type to fit you.Links of London are made in high quality and magnificent design. In our Tiffanysjewellery rings collection, you can find classical, elegant and various styles of rings. And all rings sizes range from 5 to 11 US size.Tiffanysjewellery.co.uk provides our customers with various kinds of fantastic, handcrafted Links of London charm which are appealing to their refined tastes.

wodahao replied on Mon, 2009/07/06 - 7:55am

http://www.guideshoes.com http://www.popfuns.com http://www.collectbag.com http://www.hojewelry.com http://www.pickforshoes.com http://www.oursimply.com http://www.lingeriesell.com http://www.hidresses.com http://www.tiffanyandlinks.com http://www.hojewelry.com http://www.jewelry66.com http://www.lingeriesell.com http://www.shoesmessage.com http://www.tiffanyandlinks.com http://www.hojewelry.com http://www.hidresses.com http://www.infashionlife.com http://www.choosehandbag.com http://www.pickforshoes.com http://www.dress4dancing.com http://www.lingeriesell.com

mimi1987 replied on Wed, 2009/11/11 - 8:12am

70-630 70-236 70-432 70-271

mimi1987 replied on Sun, 2009/11/15 - 10:09pm

<a href="http://www.certsecret.com/tag/70-643/">70-643</a></br> <a href="http://www.certsecret.com/tag/70-630/">70-630</a></br> <a href="http://www.certsecret.com/tag/70-236/">70-236</a></br> <a href="http://www.certsecret.com/tag/70-432/">70-432</a></br> <a href="http://www.certsecret.com/tag/70-271/">70-271</a></br>

mimi1987 replied on Wed, 2009/11/18 - 7:42am

If you are a student in school, or you want to enter the IT industry, passing 70-643 70-630 70-236 70-432 70-271 exam and obtaining Microsoft certification at least shows that you are really making your efforts and have acquired the knowledge and skills in this field.This certificate will help you lead your competitors, help you win an opportunity.

mimi1987 replied on Wed, 2009/11/18 - 7:42am

The continuous development of high technology drives up the demands for IT talents on a yearly basis.Despite the economic ups and downs, the trend of informationize will not turning back but only goes further and increase. 70-431 70-640 70-642 70-401 70-293

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.