Hacking with PHP is being updated for PHP 7: pre-order for only $10! >>

Reading from a string

While simplexml_load_file() loads XML data from a file, simplexml_load_string() loads XML data from a string. This is generally not as useful, but it does allow you to easily load several XML files into one string, then use that inside one SimpleXML structure.

Take a look at the following script:

$employees = <<<EOT <employees>
<employee ID="2" FOO="BAR">
<name>Anthony Clarke</name>
<title>Chief Information Officer</title>
<employee ID="2" BAZ="WOM">
<name>Laura Pollard</name>
<title>Chief Executive Officer</title>
</employees> EOT;   $employees = simplexml_load_string($employees);

foreach ($employees->employee as $employee) {
    print "{$employee->name} is {$employee->title} at age {$employee->age}\n";

As you can see, the majority of the script is just there heredoc-style string assignment that sets up the XML. Then, with a call to simplexml_load_string(), the XML is parsed into the $employees object, just as with the simplexml_load_file() function. The resulting object is no different, as can be seen with the output from the foreach loop.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Searching and filtering with XPath >>

Previous chapter: First steps

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.