DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Creating XML Documents in PHP

Creating XML Documents in PHP

Charlie Key user avatar by
Charlie Key
·
Jan. 23, 09 · News
Like (2)
Save
Tweet
Share
93.26K Views

Join the DZone community and get the full member experience.

Join For Free

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.

XML PHP Document

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Hackerman [Comic]
  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • Why You Should Automate Code Reviews
  • Ultimate Guide to FaceIO

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: