How to Read an XML File

Sometimes, it’s easier to use XML files instead of a database. I like to use XML files for variables that don’t change much, or when there is a limited amount of persistent data, such as you would find in configuration files.

If I don’t need to do a lot of searching or indexing on the data, sometimes it’s easier to just use XML for data persistence. It’s also a wise choice for sharing information between websites.

PHP’s SimpleXML makes reading XML files easy. To access the elements of the file, it helps to know the structure of the xml file. If you don’t know the layout of the xml file, then you probably shouldn’t use simpleXML. There are other ways, but they are posts for another day.

Since I know how my XML file is structured, I can use simpleXML.

I have the following XML file:


Of course this is a very abbreviated example so that I can make my point a little clearer. I have an xml file of people and each person is a separate ‘person’ element node in the file.

To load the xml file into an object, I use this:

$xml = simplexml_load_file('path/to/file.xml');

Now, I can access the elements in the file like this:

echo $xml->person[0];
echo $xml->person[1];

Or this:

foreach ($xml->person as $person) {
  echo $person;

Of course, most xml files are a little more complex than this and you can have element nodes nested in other element nodes, but the same rules apply moving down through the nesting. Assuming my xml file above had more elements inside the person node, I could do something like this:

foreach ($xml->person as $person) {
  echo $person->name;

Can’t get much easier than that!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top