How to parse XML using XPATH and PHP

Okay, I’m back in the saddle for an easy tutorial about parsing XML using XPATH and PHP. Say what?  Ah, let me say it in again using english. 🙂

In our first tutorial, we covered how to make an API call to create a CCB profile.  Nevertheless, when using CCB’s API library to make API calls, it is inevitable that you’ll encounter a need to retrieve and display data from the API’s XML response information.

In its native form, XML can be quite intimidating if you have never worked with it.  But don’t fear, because after this tutorial, you’ll have a better understanding of XML, and how to parse XML using XPATH to retrieve and display the desired data points.  Are you ready to get started?  Let’s go!

Creating a sample XML response

If you’ve taken the time to review CCB’s API documentation, then it didn’t take you long to realize that it referenced both cURL and XML.  Plainly stated, the documentation reads much like, “Hey, you use cURL to make X service call and it will return you Y XML response”.

So just what is this XML business that I reference?  For starters, it’s called EXtensible Markup Language and is a cousin to HTML. In short, XML is a data structure that is used to describe data and not display data like HTML.  When you think of XML, just think about giving data an organized structure or hierarchy.

For example, let’s use my family.  There are 4 individuals in our family for now: Myself, My wife and our two precious boys.  Each individual in our family would be known as a distinct element in XML terms.  Elements always contain a start tag (e.g., <response>) and an end tag (e.g., </response>) with a value in between, and can contain a variety of attributes (e.g., id=”100″). Use the provided link to learn more about XML elements.  I press forward now.

Using my family, create an XML response to group my family as individuals, and then sub-categorize each individual with their respective first name, last name, and full name elements and age attribute (see code example below).

Open your text editor of choice, and create and save a file called xml-xpath.php.  Start your document with the necessary PHP start tag (i.e., <?PHP ) and end tag (i.e., ?>).  Now add a few blank lines using your enter key between the PHP start and end tags, and create a xmlContent variable.

To create the XML string, use <<<XML to start and XML; to end.  Your XML elements, their attributes and values will between <<XML and XML;.  Notice structure of the XML sample code to create an XML response and how it’s very much outlined as the following bulleted list and my statement above about using my family:

  • one response element
    • one individuals element with attribute count of 4 to signify one family of four
      • multiple individual elements with their respective attribute age
        • respective first name, full name and last name elements

Notice that each element contains its respective start and end tags, values in between, and attributes where rendered.  And this is how you create a simple xml string using a PHP variable.

Accessing XML response data

We have our XML variable and response created, so now we are ready to access the XML response data.  To do so, we’ll create a xml variable and use PHP’s SimpleXMLElement class to access and prepare the data for parsing, passing the xmlContent variable as its argument.

Navigating the prepared XML response data

We have our xmlContent variable with XML response. Check.  We have assigned a xml variable and have prepared the xmlContent variable to be accessed using SimpleXMLElement. Check.

Now we are ready to navigate our XML tree-structure like response using XPATH and display the data to the web browser as shown in the example bulleted list below.

  • Alvin Brown (34)
  • Mallary Brown (31)
  • Ian Brown (1)
  • Seth Brown (0)

Don’t fret if you’ve never used XPATH, but do take time to read through the XPATH introduction to gain a better understanding.  It’s quite easy to learn and use, and this built-in function will save you quite a bit of time when you’re wanting a friendly method to navigate XML elements and attributes.

For the sake of time, I’m not going to expound on XPATH too much, but will try to help you understand simple thoughts about it.

Simply put, XPATH syntax is made up of expressions.  In this example, we’ll use the // and nodename expression to provide the ability to search and match nodes to XML elements and attributes. In our example, we’re attempting to find each individual and their respective elements and attributes.

Create a nodes variable, and a xpath query to search for expression //individuals/individual using the -> object reference to access the xml variable prepared XML response data.  Now that you have a nodes variable, we’ll iterate or repeat a PHP foreach loop statement to access the prepared XML data of each individual found or matched using the xpath query expression //individuals/individual.

Create a foreach statement and pass to it the nodes variable as a single node, which nodes currently contains the prepared XML data response via SimpleXMLElment in an array object.  Once inside the foreach statement, access the XML element value of each individual using node->elementname.  To access the age attribute of each individual, use node[“age”].

Also notice that I created an empty allPersons variable before the foreach statement, and then I continue to use it within the foreach statement.  Also notice that I use .= operator and not = operator when using the allPersons variable within the foreach statement.  This .= operator allows string concatenation (i.e., this + that = thisthat) and it is a PHP string operator that you should get to know intimately.

Finally, we’re ready to now display the list of bulleted individuals to the web browser using PHP echo as shown below at the very end of the codebase.

Time to assemble your xml-xpath.php file, saving and testing it

Well, you’ve made it to the very end of this tutorial!  It’s time to assemble the entire codebase in the xml-xpath.php file and test it in your web browser.

If you’re using XAMPP, then you’ll want to place this file in your htdocs folder and use localhost to access it (e.g. http://localhost/xml-xpath.php).

If you’re using a 3rd-party web hosting provider, then you’ll want to upload the file to your root web directory folder, accessing the file using the domain or ip address of your web server (e.g., or

Well, that’s a wrap on this tutorial and now you know how to parse XML using XPATH and PHP.

Moving forward, we’ll reference this tutorial from time to time as we explore a variety of CCB API calls to retrieve, parse, display and save XML data for use in 3rd-party applications or within CCB.

Well, I’m signing off… happy parsing until the next tutorial!

Please comment if this tutorial has helped you.