Hudzilla.org - the homepage of Paul Hudson
Contents > XML & XSLT > SimpleXML Wish List | Report Bug | About Me ]

12.3.2     Reading from a string

This 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.





<< 12.3.1 First steps   12.3.3 Searching and filtering with XPath >>
Table of Contents
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!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 07 Sep 2008

$employees = simplexml_load_string($employees);

I think that renaming this var $xml would be less confusing:

foreach ($xml->employee as $employee) {

is better understood than..

foreach ($employees->employee as $employee) {



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is three plus one?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow