PHP simplexml_load_string() Function
Example
Convert an XML string into an object, then output keys and elements of the object:
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
Run Example »
Definition and Usage
The simplexml_load_string() function converts a well-formed XML string into an object.
Syntax
simplexml_load_string(data, class, options, ns, is_prefix)
Parameter Values
Parameter | Description |
---|---|
data | Required. Specifies a well-formed XML string |
class | Optional. Specifies the class of the new object |
options | Optional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
|
ns | Optional. Specifies a namespace prefix or URI |
is_prefix | Optional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE |
Technical Details
Return Value: | A SimpleXMLElement object on success. FALSE on failure |
---|---|
PHP Version: | 5+ |
More Examples
Example
Output the data from each element in the XML string:
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
Run Example »
Example
Output the element's name and data for each child node in the XML string:
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>
Run Example »
❮ PHP SimpleXML Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.