The simplexml_load_string() function converts a well-formed XML string into a SimpleXMLElement object.
Syntax for PHP simplexml_load_string() Function has the following syntax.
simplexml_load_string(data,classname,options,ns,is_prefix);
Parameter | Is required | Description |
---|---|---|
data | Required. | A well-formed XML string |
classname | Optional. | Class of the new object |
options | Optional. | Additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) |
ns | Optional. | Namespace prefix or URI |
is_prefix | Optional. | TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE |
Possible values for options:
Returns a SimpleXMLElement object on success. FALSE on failure.
Convert a well-formed XML string into a SimpleXMLElement object, then output keys and elements of the object:
<?php//w ww .j a va 2 s.c o m
$note=<<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<book>
<name>PHP</name>
<name>Java</name>
</book>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
The code above generates the following result.
Output the data from each element in the XML string:
<?php//from w w w. j a v a 2s. co m
$note=<<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<book>
<name>PHP</name>
<name>Java</name>
</book>
XML;
$xml=simplexml_load_string($note);
echo $xml->to . "\n";
echo $xml->from . "\n";
echo $xml->heading . "\n";
echo $xml->body;
?>
Output the element's name and data for each child node in the XML string:
<?php//www . ja v a 2 s . co m
$note=<<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<book>
<name>PHP</name>
<name>Java</name>
</book>
XML;
$xml=simplexml_load_string($note);
echo $xml->getName() . "\n";
foreach($xml->children() as $child){
echo $child->getName() . ": " . $child . "\n";
}
?>
The code above generates the following result.