Parsing selected parts of XML file with PHP

I’m a beginner at processing XML with PHP. I have just started reading about SimpleXML and related methods of parsing data from XML files, but I’m struggling with it. Once PHP has the data, I’ll be in fairly familiar territory, but the part before that is not so easy!

The examples that I have so far seen show how to, for instance, find and display all names from an address book or all titles from data about books. But I would like to know if it is possible to fetch selected sets of data from a small XML file (maybe 50-60 datasets) based on certain criteria, which are:

  1. The first 5 entries
  2. Entries that match certain categories

An example of one complete dataset would be something like this:

<date>01 May 2010</date>
<title>Page title</title>
<desc>Description of page</desc>

I understand that a CMS can do this sort of thing and more, but that wouldn’t be the right solution for me (I’m happier when just coding my own pages) and would entail changing my service provider (and paying a lot more).


You can use simplexml and xpath in order to parse xml files. Just use simplexml to load your file ex:

$xml = simplexml_load_file('test.xml');

After that you can use Xpath to obtain the elements you need from the xml in the form of an array of objects ex :

$result = $xml->xpath('/title');

After that you can use foreach to go through the result set and process data.

Take a look here for an example.