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:

<?php
$employees = <<<EOT <employees>
<employee ID="2" FOO="BAR">
<name>Anthony Clarke</name>
<title>Chief Information Officer</title>
<age>48</age>
</employee>
<employee ID="2" BAZ="WOM">
<name>Laura Pollard</name>
<title>Chief Executive Officer</title>
<age>54</age>
</employee>
</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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

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.