PHP Function Reference

PHP SimpleXMLElement - __construct() Method



The PHP SimpleXMLElement::__construct() method creates a new SimpleXMLElement object.

Syntax

public SimpleXMLElement::__construct(data, options, dataIsURL, 
                                     namespaceOrPrefix, isPrefix)

Parameters

data Required. Specify a XML string or the path or URL to an XML document if dataIsURL is true.
options Optional. Use this parameter to specify additional Libxml parameters, which affect reading of XML documents.
dataIsURL Optional. If set to true the data is considered as a path or URL to an XML document instead of string data. Default is false.
namespaceOrPrefix Optional. Namespace prefix or URI.
isPrefix Optional. If true, namespaceOrPrefix will be regarded as a prefix. If false, namespaceOrPrefix will be regarded as a URI. Default is false.

Return Value

Returns a SimpleXMLElement object representing data.

Exceptions

Produces an E_WARNING error message for each error found in the XML data.

Note: Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Example: creating a SimpleXMLElement object

In the example below, this method is used to convert the given XML string to a SimpleXMLElement object.

<?php
$xmlstr = <<<XML
<userlist> 
  <user id="John123">
    <name>John Smith</name>
    <city>New York</city>
    <phone>+1-8054098000</phone>
  </user>
  
  <user id="Marry2015">
    <name>Marry G.</name>
    <city>London</city>
    <phone>+33-147996101</phone>
  </user> 
</userlist> 
XML;

$xml = new SimpleXMLElement($xmlstr);
 
print_r($xml);
?>

The output of the above code will be:

SimpleXMLElement Object
(
    [user] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [id] => John123
                        )

                    [name] => John Smith
                    [city] => New York
                    [phone] => +1-8054098000
                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [id] => Marry2015
                        )

                    [name] => Marry G.
                    [city] => London
                    [phone] => +33-147996101
                )

        )

)

Example: creating a SimpleXMLElement object from a URL

In the example below, a SimpleXMLElement object is created from a URL.

<?php
$xml = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $xml->asXML();
?>

❮ PHP SimpleXML Reference