![]() |
More and more in the new concept of the web sites share data. The most common type of this data is shared via XML file documents. You’ll for sure know about RSS: they are xml files. What about sites like WowHead? They allow you to access all their database via XML. Well, let’s learn how to read an XML file!
First of all: XML has its own syntax. It has tags, just like HTML. The first line says which version of XML you’re reading and the encoding you’re using, like this:
<?xml version="1.0" encoding="UTF-8"?>
This shouldn’t be that important for you but if you’re looking for a not common XML file.
The second line should begin the data. This is the example we’re going to use:
<?xml version="1.0" encoding="utf-8"?>
<articles>
<article id="1">
<title>Article one</title>
<author>Myself</author>
</article>
<article id="2">
<title>Article two</title>
<author>My friend</author>
</article>
<article id="3">
<title>Article three</title>
<author>The friend of a friend</author>
</article>
</articles>
As you can see there are categories, variables and so on. We’ll talk more about it in the tutorial about writing an XML file.
So, there are more then one classes in PHP on how to read an XML file. Recently PHP5 intrduced the SimpleXML class. It’s a powerful class and I learnt it very quickly.
The first thing to do is to create this new class entity, loading the external file: it can be loaded from a relative or absolute path or from an URL.
$xml = simplexml_load_file('articles.xml');
Ok, now we have the file loaded in the system! You can call the variables in a very easy way, using the arrows ($xml->article[0]->title). Of course the “properties” in the “tags” can be accessed like an array ($xml->article[0]["id"]).
foreach($xml->article as $article)
{
echo "Article ID: ".$article['id']."<br />";
echo "Article title: ".$article->title."<br />";
echo "Article author: ".$article->author."<br />";
}
I’ll talk more about the foreach cycle in another tutorial, but the basics are that foreach takes as arguments “$array as $new_variable”. The cycle ends when all the objects in the array have been processed. In this case $xml is an array with three “article” sub-variables. The cycle will take them and treat each of them as a stand-alone variable.
Easy, isn’t it?


