Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating XML Documents in PHP

DZone's Guide to

Creating XML Documents in PHP

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

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.

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Charlie Key. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}