Home About Contact DOTW RSS

Get Social with GeekZenith...

Parsing XML with XPATH & PHP Part One

Over the years as a developer I’ve found the combination of XML and PHP to be a potent one; creating dynamic web pages based on XML and PHP, which update and maintain themselves is a great aid to a developer when used correctly and a fantastic time saving device.

In this two-part tutorial I will show you how to parse XML data with PHP and XPath, display the XML data and to use this parsed data to create a dynamic PHP headline and content system.

I’m going to assume the readers of this tutorial know their way around PHP and know the basics of the uses of XML (if not I heartily recommend either Tizag or W3 Schools), so let’s get a brief description:

“XPath is a language for finding information in an XML document.”

It’s as simple as that. The function itself is easily enough to inplement if you know what you’re doing and I’ll be going through how to use it to extract XML data in this tutorial.

Let’s get to it, shall we?

In this tutorial we will have three files to make this work; the XML file (I’ve rather imaginatively called mine xml.xml), the file with the list of linked fixtures (I’ve called my file headlines.php) and the pop-up file where the match description will be called to from headlines.php (I’ve called this file story.php).

Firstly, let’s examine the XML file we’ll be working off below:


<worldcup>
<day id="1">
    <game id="1" name="South Africa v Mexico" date="11/06/2010" time="17:30">
    This is a bit of description about the the South Africa vs Mexico Game.
    </game>
    <game id="2" name="Uruguay v France" date="11/06/2010" time="19:30">
    This is a bit of description about the the Uruguay vs France Game.
    </game>
</day>
<day id="2">
    <game id="3" name="South Korea v Greece" date="12/06/2010" time="17:30">
    This is a bit of description about the the South Korea vs Greece Game.
    </game>
    <game id="4" name="Argentina v Nigeria" date="12/06/2010" time="17:30">
    This is a bit of description about the the Argentina vs Nigeria Game.
    </game>
    <game id="5" name="England v USA" date="12/06/2010" time="17:30">
    This is a bit of description about the the England vs USA Game.
    </game>
</day>
</worldcup>

As you can see, the XML data is based around the impending World Cup, or the first two days at least. Our intent is to display each fixture on one page, along with the date and kick off time. We will then link each game to a pop-up window displaying the game description for the selected fixture i.e. the South Africa v Mexico fixture will link to a pop-up window with the ‘This is a bit of description about the the South Africa vs Mexico Game.’ description.

Let’s move on to constructing the ‘headlines’ page. Here we will be calling to the XML and parsing the fixtures data into links.

The first thing we need to do, is call to our XML file in the PHP and assign it to a variable as seen below:

<?PHP

$xml = simplexml_load_file("xml.xml");

?>

The next step is to get the XPath to extract the data from the XML and assign to a variable:

<?PHP

$xml = simplexml_load_file("xml.xml");

$game = $xml->xpath("//game");

?>

As you can see from above, we’re getting the XPath to read the XML file and then we’re directing it to the game node of our XML file. If you we wanted to get the day id, then the code would read $xml->xpath(“//day”);. The ‘//’ is merely telling the XPath to ‘jump to’ the game node.

So now we’ve called to the XML file and we’ve the XPath to read it. This has put the data in an array within the $game variable and to extract the data we require we must tell the variable which of the game nodes we want to display. For example:


<?PHP

$xml = simplexml_load_file("xml.xml");

$game = $xml->xpath("//game");

echo $game[0]['name'];

?>

Let’s break this down:

$game[0] = we’re telling the variable to start at the very first game node of our XML file.
['name'] = we’re telling variable to locate the name attribute to be displayed.

So, to put this is into perspective, say we wanted the kick off time of the Argentina v Nigeria match, we use $game[3]['time'];.

But calling to each game in the array is inneffcient and certainly not dynamic, so the better way is to loop through the array to extract each data node. In order to do this, we must first set the counter variable to 0. We set it to 0 because as we already know how first data node in the variable array is 0 and therefore it must loop through 0 first.:

<?PHP

$xml = simplexml_load_file("xml.xml");

$game = $xml->xpath("//game");

$i = 0;

?>

Next it’s time to set the loop up. For this, I generally prefer using the while loop, so:


<?PHP

$xml = simplexml_load_file("xml.xml");

$game = $xml->xpath("//game");

$i = 0;

while()
{

}

?>

Now we must determine when we want the loop to stop. In our sample XML file we have 5 game nodes, so the max is 5 nodes. Some users might want to determine a set number to show the lasrt 5 or 10 data nodes in the file, however, some user might want to use all the data nodes in their XML file. If it’s the latter, we can use the PHP Count funtion to determine how many data nodes are in the XML file with the below addition in the code and set the while to go through the array and display all of the data:

<?PHP

$xml = simplexml_load_file("xml.xml");

$game = $xml->xpath("//game");

$count = count($game);

$i = 0;

while($i < $count)
{

}

?>

Next, we tell the code to display the data we need and also add 1 to the counter variable, $i, ad the end of the loop so that it goes through the same process so long as the counter variable is less than the total number of data nodes we assigned to the $count variable:


<?PHP

$xml = simplexml_load_file("xml.xml");

$game = $xml->xpath("//game");

$count = count($game);

$i = 0;

while($i < $count)
{

echo '<h1<'.$game[$i]['name'].'</h1<';
echo 'Kick Off on '.$game[$i]['date'].' @ '.$game[$i]['time'];

$i++;

}

?>

Download Files for this Tutorial

Next up: Parsing XML with XPATH in PHP Part Two – Creating the Dynamic pop-up Content System

Looking to Learn a little more about PHP? I recommend this book entirely.

But meanwhile, if you have any queries about this first part of the tutorial please don’t hesitate to ask below.

Like this fantastical post on Facebook!

Share this awesometastic post with your friends on Facebook!

5 Responses to “Parsing XML with XPATH & PHP Part One”

  1. streec says:

    this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
    copy of this lesson on my site here

    http://www.streec.com/vb

  2. The Master of Awesomeness says:

    Thanks Streec! Much appreciated!

  3. Ronald says:

    Hi.

    Great Tutorial. It really helped me.

    But what if I wanted to display the data from the XML file in a table that displays the Day, and the games that fall within that day, then Day 2 and the games for that day.

    Eg:

    Day 1

    Game: South Africa v Mexico
    Date: 11/06/2010
    Time: 17:30

    Game: Uruguay v France
    Date: 11/06/2010
    Time: 19:30

    Day 2

    Game: South Korea v Greece
    Date: 12/06/2010
    Time: 17:30

  4. Anamaria says:

    Thanks, your tutorial just save my life :)

  5. The Master of Awesomeness says:

    No problem Anamaria, glad it helped you :)

Leave a Reply