12.3.2 Reading from a stringThis is NOT the latest copy of this book; click here for the latest version.
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 see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|