Web standards books praise the idea of separating presentation from content. Unfortunately doing so is harder said than done in the professional world. When I begin working on a re-design I usually find myself spending countless hours re-formatting content, so what’s the point? If a client wants specific information laid out as an unordered list (or outline) one day and tabular data the next you’ll find yourself rebuilding the pages structure.

The best solution to this ongoing probably is to utilize XML to describe the content as best as possible. The one problem with this approach is that parsing that XML into usable code is usually a big pain in the ass. With PHP5’s implementation of the SimpleXML object parsing XML is finally as simple as it should be.

This is the best way to handle web content in my opinion. The advantages as I see them are:

  • Store your content in one central location, even it is used in multiple places throughout a site
  • Write your content once using the most semantic markup of all, XML
  • Loop through tags to make styling repeated content a breeze (e.g. Press Releases page)
  • Use your content with different technologies. Create RSS feeds, supply it to other domains or use it with Flash

Using the SimpleXML object

Let’s get our hands dirty and see how to parse an XML file with SimpleXML.

XML



	
August 26 2008 pdf/consumer-brochure.pdf New press release! Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua...

PHP


title ?>

description ?>

Published date ?>, year ?>

XHTML (generated by SimpleXML)

New press release!

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua...

Published August 26, 2008

Download source

Download the SimpleXML Source Code for the example above.

Recommended Reading

I was introduced to the SimpleXML object while browsing PHP 5 Recipes: A Problem-Solution Approach. I would recommend this book to professional developers looking for a great desk reference resource. As best put by the author, “This book is a source of instant solutions, including countless pieces of useful code that you can just copy and paste into your own applications, giving you answers fast and saving you hours of coding time.” That said, it’s big, long, and definitely not something you sit down and actually read. It provides a well documented reference of PHP 5 that includes some of the newer additions such as SimpleXML.

Resources