SimpleXML (Page 1 of 5 )
Learn an easy way to parse XML and output it the way you want by using the simpleXML extensions in PHP5. Murray outlines the 3 main elements of an XML document and how to replace them with your own non-template data and how to build an array of all the tags put in the document.
SimpleXML project primer:
To the new PHP programmer, XML is quite the mysterious thing. Recently I began writing a website that uses an XML template system, so I needed to find an easy way to parse my XML, and output it the way I needed it to be outputted. With PHP4 you have to build your own XML parser that will read and output your XML. So, with that idea I decided begin to explore PHP5, because of its simpleXML extensions.
Before jumping ahead and just building my parser, I knew that I’d have to replace elements in the XML document with data from my database; after all what would be the point of using XML for a template system if you couldn’t replace elements with your own data. So, keeping that in mind I know that I’d have to load each element of my XML document into a variable then send it through my own function to replace the things I need to replace, with the correct information. Now, let’s get started.
The first thing we should look at is the XML document. This is a simpler version of mine, but it’s still the same basic idea. Save the following as template.xml.
<?xml version="1.0" encoding="UTF-8" ?>
<template>
<header>
<![CDATA[
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><!title></title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align:center;"><!logo></td>
</tr>
</table>
]]>
</header>
<body>
<![CDATA[
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width=”15%”><!column1></td>
<td width=”70%”><!column2></td>
<td width=”15%”><!column3></td>
</tr>
</table>
]]>
</body>
<footer>
<![CDATA[
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align:center;"><!footer></td>
</tr>
</table>
</body></html>
]]>
</footer>
</template>
Next: Replace Tags with Our Data >>
More XML Articles
More By James Murray