Chapter 19. XML & XSLT

This chapter covers XML parsing and manipulation using PHP, and requires that you have some familiarity with XML, although XML syntax and grammar are not mentioned in detail—the focus is PHP.

SimpleXML

PHP offers several different ways of parsing XML, but as of PHP 5, the most popular way is to use the SimpleXML extension. SimpleXML works by reading in the entire XML file at once and converting it into a PHP object containing all the elements of that XML file chained together in the same way. Once the file has been loaded, you can simply pull data out by traversing the object tree.

The advantage of SimpleXML is that you no longer need to write any complicated code to access your XML—you simply load it, then read in attributes as you would expect to be able to. Consider the following XML file, employees.xml:

    <employees>
            <employee>
                    <name>Anthony Clarke</name>
                    <title>Chief Information Officer</title>
                    <age>48</age>
            </employee>

            <employee>
                    <name>Laura Pollard</name>
                    <title>Chief Executive Officer</title>
                    <age>54</age>
            </employee>
    </employees>

The base element is a list of employees, and it contains several employee elements. Each employee has a name, a title, and an age. Now take a look at this basic SimpleXML script:

    $employees = simplexml_load_file('employees.xml');
    var_dump($employees);

Here is the output:

 object(simplexml_element)#1 (1) { ["employee"]=> array(2) { [0]=> object(simplexml_element)#2 (3) { ["name"]=> string(14) "Anthony Clarke" ["title"]=> string(25) ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.