Outputting XML

string asXML ( [void ])

One of the most interesting features about SimpleXML is that it can, at any time, give you a string containing the well-formed XML representation of its data. This essentially does the opposite of simplexml_load_file(), but the best bit about it is that it incorporates any changes you've made to the data whilst it was in SimpleXML form.

For example:

$xml = simplexml_load_file('employees.xml');
    $xml->employee[1]->age = 55;
    echo $xml->asXML();

That loads our XML file, and changes the second employee (remember, it's a zero-based array, so the 1 actually refers to the second element) to have an age of 55. The call to asXML() then outputs the changed data tree, printing this:

<?xml version="1.0"?>
<employees>
        <employee>
                <name>Anthony Clarke</name>
                <title>Chief Information Office</title>
                <age>48</age>
        </employee>

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

Note the changed value for Laura's age. However, blindly changing values isn't a smart move: the XML could change quite easily so that Pollard was no longer the second person in there. Instead, you should really combine it with an XPath search, like this:

<?php
    $xml
= simplexml_load_file('employees.xml');
    echo
"\nBefore transformation:\n\n";

    echo
$xml->asXML();

    
$xml->employee[1]->age = 55;

    
$employees = $xml->xpath('/employees/employee[name="Anthony Clarke"]');
    
$employees[0]->title = "Chairman of the Board, Chief Information Office";

    echo
"\n\nAfter transformation:\n\n";
    echo
$xml->asXML();
?>

This time the age is changed by referencing Laura directly, but I've also changed the job title of Anthony Clarke using a smart XPath search for his exact name. Of course, even names can be duplicated by chance, so an employee ID would be even better!

 

Next chapter: Transforming XML using XSLT >>

Previous chapter: Searching and filtering with XPath

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar