O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required