Open In App

PHP | SimpleXMLElement::__construct() Function

Pre-requisite:XML The __construct() function is an inbuilt function in PHP that is used to create a new SimpleXMLElement object for XML. 

Syntax:



SimpleXMLElement::__construct( $data, $options, $data_is_url, $namespace, $is_prefix )

Parameters: This function accepts five parameters as mentioned above and described below:

Return Value: It returns a SimpleXMLElement object that represents the XML structured data 



Note: This function is available for PHP 5.0.1 and newer versions. 

Example 




<?php
 
// Loading XML document to $user
$user = <<<XML
<user>
<username> user123 </username>
<name> firstname lastname </name>
<phone> +91-XXXXXXXXXX </phone>
<detail> I am John Doe. Live in Kolkata, India. </detail>
</user>
XML;
 
// Creating new SimpleXMLElement
// object from $user
$xml = new SimpleXMLElement($user);
 
// Printing as XML
echo $xml->asXML();
 
?>

Output:

user123 firstname lastname +91-XXXXXXXXXX I am John Doe. Live in Kolkata, India.

Output in browser as source: 

Example: Loading XML document from file or url. sample.xml 




<?xml version="1.0"?>
<user>
<username> user123 </username>
<name> firstname lastname </name>
<phone> +XX-XXXXXXXXXX</phone>
<detail> I am John Doe. Live in Kolkata, India. </detail>
</user>

index.php 




<?php
 
// Loading XML document from sample.xml to $user
// and creating new SimpleXMLElement object
$xml = new SimpleXMLElement("sample.xml", 0, TRUE);
 
// Printing data as xml document
echo $xml->asXML();
 
?>

Output:

user123 firstname lastname +91-XXXXXXXXXX I am John Doe. Live in Kolkata, India.

Output in browser as a source: 

Possible values of the parameter $option are:

Reference: https://www.php.net/manual/en/simplexmlelement.construct.php


Article Tags :