Convert XML to Associative Array in PHP

XML (Extensible Markup Language) is one type of markup language that is used to store the data in a human-readable format. It is different from other markup languages. Every tag of this language is user-defined. Using XML is the better solution to store a small amount of data when you don’t want to use any database for storing data. The data from the XML document can be easily accessed and used in any web application using a PHP script. How the XML document can be parsed and stored into an associative array is shown in this tutorial.

Necessary Functions

Some built-in functions are used to convert the XML content into an associative PHP array. The purposes of different functions are explained below.

file_get_contents():

This function returns the string data by converting any XML data. It takes any XML file name as an argument.

simplexml_load_string():

This function returns the XML object by converting the XML string data. It takes XML string data as an argument.

simplexml_load_file():

This function returns the XML object by converting XML file content. It takes the XML file name as an argument.

SimpleXMLElement():

It is used to create an XML object from XML data. It takes the XML content value as an argument.

json_encode():

It returns the JSON object by converting the XML object. It takes the XML object variable as an argument.

json_decode():

It returns the associative PHP array by converting JSON data. It takes the JSON object variable as an argument.

Create XML File

You will be required to create an XML file or define XML data in the script to know the way in converting XML data into an associative PHP array. Create an XML file named courses.xml with the following content and store it in the location where the PHP script is. The file contains child elements under a parent element. So, a two-dimensional associative array will generate after converting the following XML file into a PHP array.

courses.xml

<?xml version="1.0"?>
<courses>
<course_title>Web Programming</course_title>
<duration>6 months</duration>
<book_list>
<book>
<name>The Joy of PHP Programming</name>
<author>Alan Forbes</author>
<publication>Plum Island</publication>
</book>
<book>
<name>PHP & MySQL Novice to Ninja</name>
<author>Tom Butler & Kevin Yank</author>
<publication>SitePoint</publication>
</book>
<book>
<name>Head First PHP & MySQL</name>
<author>Lynn Beighley & Michael Morrison</author>
<publication>O’Reilly</publication>
</book>
</book_list>
</courses>

Example-1: Convert XML file content into an associative array without checking error

The following script shows the uses of file_get_contents() and simplexml_load_string() functions to create XML object. Here, the courses.xml file is used for conversion that was created before. Next, json_encode() and json_decode() function are used to get the associative array after converting the XML file content. If no error exists in the XML content, then no error will be shown by the following script. Here, <pre> tag is used to print the array in a formatted way.

<?php

//Define the existing XML file
$xml = "courses.xml";

//Read the full contents of the XML file as XML string
$xmlData = file_get_contents($xml);

//Convert XML string data into XML object
$xmlObject = simplexml_load_string($xmlData);

//Convert XML object into JSON object
$jsonObject = json_encode($xmlObject);

//Convert JSON object into an associative array
$assArray = json_decode($jsonObject, true);

//Print the structure of the associative array
echo "</pre>
<pre>"
;
print_r($assArray);
echo "</pre>
"
;

?>

Output:

The following output will appear after executing the PHP script. Here, a two-dimensional array is generated based on the content of the XML file, courses.xml.

Example-2: Convert XML file content into an associative array with checking error

It is better to check error when converting XML into an associative array. It will help the coder to debug the code if the error checking is implemented in the script. The following script shows the ways to convert XML file content into an associative array by using simplexml_load_file() function with error handling. The libxml_use_internal_errors() function is used with TRUE value to enable the error handling. If the XML file content that is used in the script contains any error then simplexml_load_file() function will return false, and the error message will be printed by using libxml_get_errors() function. If no error exists in the XML file, then the content of the file will convert properly into a two-dimensional associative array.

<?php

//Enable user error handling
libxml_use_internal_errors(TRUE);

//Create XML Object
$objXml = simplexml_load_file("courses.xml");

//Print error if the XML object returns false
if ($objXml === FALSE) {
echo "There were errors parsing the XML file.\n";
foreach(libxml_get_errors() as $error) {
echo $error->message;
}
exit;
}

//Convert XML object into JSON object
$objJson = json_encode($objXml);
//Convert JSON object into an associative array
$assarr = json_decode($objJson, TRUE);

//Print the structure of the associative array
echo "<pre>";
print_r($assarr);
echo "</pre>";

?>

Output:

The following output will appear after executing the PHP script. Here, no error exists in the XML file. So, a two-dimensional array has generated like the previous example based on the content of the XML file, courses.xml.

Example-3: Convert XML content into an associative array

The following script shows the way of converting XML data into an associative array by using SimpleXMLElement() function. In the script, the XML content is stored into a variable named $xml that is used as the argument of the function, SimpleXMLElement(). Next, json_encode() and json_decode() function are used to get the associative array after converting the XML file content.

<?php

//Define the XML variable
$xml = <<<XML
<?xml version='1.0' standalone='yes'?>
<customers>
<customer name="Jolly">
<email>jolly@example.com</email>
<address>
<street>12/A, Dhanmondi</street>
<city>Dhaka</city>
</address>
</customer>
<customer name="Jafar">
<email>jafar@example.com</email>
<address>
<street>156, Motijeel</street>
<city>Dhaka</city>
</address>
</customer>
<customer name="Jony">
<email>jony@example.com</email>
<address>
<street>21/B, Mogbazar</street>
<city>Dhaka</city>
</address>
</customer>
</customers>
XML
;

//Create XML object
$xmlObject = new SimpleXMLElement($xml);
//Create JSON Object
$jsonObject = json_encode($xmlObject);
//Convert JSON object into an associative array
$assArray = json_decode($jsonObject, true);

//Print the structure of the associative array
echo "<pre>";
print_r($assArray);
echo "</pre>";

?>

Output:

The following output will appear after executing the PHP script. Here, a two-dimensional array is generated based on the content of the XML variable, $xml.

Conclusion:

There were three different ways of converting XML content into an associative array that was shown in this tutorial. This will help the readers to know the way to work with XML data and parse the data from the XML content by using a PHP script easily.



from Linux Hint https://ift.tt/32nYK0Q

Post a Comment

0 Comments