With the addition of certain very help PHP functions that were released in version 5.0, the integration of XML and PHP is now simpler then ever.
Why XML over a database driven solution? I could discuss all the reasons for and against but at the end of the day in a case like a photo gallery it really comes down to personal preference. For me its all about ease of use and not adding complexity to something that at its core should be very easy and straight forward. XML offers accessibility, readability, flexibility and you don’t need to start playing with database tables and fields to achieve results fast.
While I endeavor to write this for the common person the below article does assume a basic understanding of XML and PHP. If you want to understand more about either topic a good starting place is the w3Schools website which offers great free introductory tutorials on standard web technology.
Download Tutorial Files
The Basics
I’ll be basing my photo gallery off a simple XML document, which I’ll detail here. Please feel free to download a copy of the source files to follow along with me. Now I don’t pretend to be an expert at writing XML, so feel free to suggest any changes in the comments section.
<?xml version=”1.0″ encoding=”ISO-8859-1″? >
<gallery title=”Random” description=”Random photos I like”>
<albumName>Random Photos</albumName>
<image>
<title>Alamo Square, SF</title>
<tnPath>thumbs/tn_alamoSquare.jpg</tnPath>
<lgPath>photos/alamoSquare.jpg</lgPath>
<tnWidth>45</tnWidth>
<tnHeight>45</tnHeight>
<width>500</width>
<height>375</height>
</image>
<image>
<title>Alcatraz, SF</title>
<tnPath>thumbs/tn_alcatraz.jpg</tnPath>
<lgPath>photos/alcatraz.jpg</lgPath>
<tnWidth>45</tnWidth>
<tnHeight>45</tnHeight>
<width>500</width>
<height>375</height>
</image>
…
…
</gallery>
This basically allows me to describe an image by giving it a title, url paths to the location of the photo and its thumbnail, and the width and height of each. I’ve decided to use relative paths for the images here although in the tutorial files I’ve used absolute paths to the image URL to add flexibility in using the code anywhere in your site.
Now, using the simpleXML function in PHP we can write some code to connect to the above XML document.
<?php
// set the XML file name as a PHP string, make
// sure the path to the xml file is correct.
$myPhotoList = “photos.xml” ;
// load the XML file
$xml = @simplexml_load_file($myPhotoList) or die (”no file loaded”) ;
?>
That’s all that’s needed to connect to our XML file. Now we can assign PHP variables with specific elements from the XML document by use the variable $xml->element as follows:
(more…)