Example 5. Comparing Elements and Attributes
with Text
To compare an element or attribute with a string or pass
it into a function that requires a string, you must cast
it to a string using (string). Otherwise, PHP treats the
element as an object.
<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);
if ((string) $xml->movie->title == 'PHP: Behind the
Parser') {
print 'My favorite movie.';
}
htmlentities((string) $xml->movie->title);
?>
Example 6. Using Xpath
SimpleXML includes builtin Xpath support. To find all <character>
elements:
<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);
foreach ($xml->xpath('//character') as $character) {
echo $character->name, 'played by ', $character->actor,
'<br />';
}
?>
'//' serves as a wildcard. To specify absolute paths, omit
one of the slashes.
Example 7. Setting values
Data in SimpleXML doesn't have to be constant. The object
allows for manipulation of all of its elements.
<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);
$xml->movie[0]->actor[0]->age = '21';
echo $xml->asXML();
?>
The above code will output a new XML document, just like
the original, except that the new XML will define Ms. Coder's
age as 21.
Example 8. DOM Interoperability
PHP has a mechanism to convert XML nodes between SimpleXML
and DOM formats. This example shows how one might change
a DOM element to SimpleXML.
<?php
$dom = new domDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$s = simplexml_import_dom($dom);
echo $s->book[0]->title;
?>
Table of Contents
simplexml_element->asXML -- Return a well-formed XML
string based on SimpleXML element.
simplexml_element->attributes -- Identifies an element's
attributes.
simplexml_element->children -- Finds children of given
node.
simplexml_element->xpath -- Runs Xpath query on XML data.
simplexml_import_dom -- Get a simplexml_element object from
a DOM node.
simplexml_load_file -- Interprets an XML file into an object.
simplexml_load_string -- Interprets a string of XML into
an object.