Open In App

PHP | simplexml_load_string() Function

Sometimes there is a need of parsing XML data in PHP. There are a handful of methods available to parse XML data. SimpleXML is one of them. Parsing an XML document means that navigating through the XML document and return the relevant pieces of information. Nowadays, a few APIs return data in JSON format but there are still a large number of websites which returns data in XML format. So we have to master in parsing an XML document if we want to feast on APIs available.

PHP SimpleXML was introduced back in PHP 5.0. The simplexml_load_string() function in PHP is used to interpret an XML string into an object.



Syntax:

simplexml_load_string($data, $classname, $options, $ns, $is_prefix);

Parameters: This function accepts five parameters as shown in the above syntax. All of these parameters are described below:



Possible Values for the parameter $options are as follows:

Return Value This function returns a SimpleXMLElement object on success and FALSE on failure.

Below programs illustrate the simplexml_load_string() function:

Program 1:




<?php
$note=<<<XML
<note>
  <to>User 1</to>
  <from>User 2</from>
  <heading>Reminder</heading>
  <body>Don't 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;
?>

Output:

User 1
User 2
Reminder
Don't forget me this weekend!

Program 2:




<?php
$note=<<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<book>
    <name>PHP</name>
    <name>Java</name>
    <name>C++</name>
    <name>Python</name>
</book>
XML;
  
$xml=simplexml_load_string($note);
echo $xml->getName() . "\n";
  
foreach($xml->children() as $child){
   echo $child->getName() . ": " . $child . "\n";
}
?>

Output:

book
name : PHP
name : Java
name : C++
name : Python

Reference :
http://php.net/manual/en/function.simplexml-load-string.php


Article Tags :