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.
$xml = simplexml_load_file('employees.xml'); $xml->employee->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->age = 55; $employees = $xml->xpath('/employees/employee[name="Anthony Clarke"]'); $employees->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!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Transforming XML using XSLT >>
Previous chapter: Searching and filtering with XPath
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.