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.

 

Next chapter: Searching and filtering with XPath >>

Previous chapter: First steps

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar