Converting XML to PHP Array: A Comprehensive Guide

In the world of web development, data interchange is a common challenge. XML (eXtensible Markup Language) is one of the widely used formats for structuring data, and PHP (Hypertext Preprocessor) is a powerful server-side scripting language. Combining these two, you might find yourself needing to convert XML data into a PHP array for efficient processing. In this guide, we’ll walk you through the process step by step.

Why Convert XML to PHP Array?

Converting XML to a PHP array simplifies data manipulation and extraction. PHP arrays offer a versatile and familiar data structure that facilitates easier handling and processing of information within the PHP environment.

“Bonus: I will provide you a function that will convert XML data to PHP array directly so you can find this function at the last step.”

 

Steps to Convert XML to PHP Array

1. Load XML Data

Begin by loading the XML data using PHP’s SimpleXML or DOMDocument classes. These classes provide convenient methods to parse and manipulate XML documents.

$xmlString = '<root><item>Hello</item><item>World</item></root>';
$xml = simplexml_load_string($xmlString);

2. Convert to JSON

Convert the SimpleXML object to a JSON string using the json_encode function. This step is crucial as JSON shares similarities with PHP arrays, making the conversion process smoother.

$jsonString = json_encode($xml);

3. Decode JSON to PHP Array

Decode the JSON string into a PHP associative array using json_decode. Now, you have your XML data in a PHP-friendly format.

$arrayData = json_decode($jsonString, true);

Handling XML Attributes

If your XML contains attributes, additional steps are needed to capture them in the PHP array. Use the attributes() method to access and include attributes in the conversion process.

foreach ($xml->item as $item) {
$attributes = $item->attributes();
$arrayData['item'][] = [
'value' => (string) $item,
'attributes' => (array) $attributes,
];
}

Practical Tips for XML to PHP Array Conversion

  • Error Handling: Implement robust error handling to manage potential issues during the conversion process.
  • Nested Structures: Handle nested XML structures by recursively converting child elements.
  • Optimizing Performance: Consider the performance implications of your chosen XML parsing method, especially for large datasets.

As I promised,  I will give you the direct solution that will convert XML data to PHP and I will explain how to use that function with the use case.

So create a php file named xml_parser.php  and copy and paste the given class.

class xml_parser {

var $dom;
var $root;
var $ret;
var $encoding;

function convert_attrs($att) {

$ret = array();

foreach($att as $i)
$ret[$i->name] = $i->value;

return $ret;

}
function parse_node($node) {
$ret = '';
$node_name = $node->nodeName;
if ( $node->hasChildNodes()) {

foreach($node->childNodes as $n) {
if ($n->nodeName == '#text' || $n->nodeName == '#cdata-section') {
if (!is_array($ret)) {
$ret = $n->nodeValue;
}
$node_value = $n->nodeValue;
}
else {
if (isset($ret) && !is_array($ret))
$ret = array();
$tmp = $this->parse_node($n);
$attrs = $n->attributes;

if ($attrs != NULL) {
$attrs = $this->convert_attrs($attrs);
if (!empty($attrs)) {
$tmp2 = $tmp;
$tmp = array();
$tmp['value'] = $tmp2;
$tmp['_attrs'] = $attrs;
}
}
if (!isset($ret[$n->nodeName])) {
$ret[$n->nodeName] = $tmp;
}
else {
if (is_array($ret[$n->nodeName]) && !isset($ret[$n->nodeName][0])) {
$switch = $ret[$n->nodeName];
$ret[$n->nodeName] = array();
$ret[$n->nodeName][0] = $switch;
}
else if (!is_array($ret[$n->nodeName]) && isset($ret[$n->nodeName])) {
$switch = $ret[$n->nodeName];
$ret[$n->nodeName] = array();
$ret[$n->nodeName][0] = $switch;
}
$ret[$n->nodeName][] = $tmp;
}
}
}
}
return $ret;
}

function parse($xml) {

$this->dom = new DOMDocument();
$this->dom->loadXML($xml);
$this->ret = array();

if (!isset($this->dom) || $this->dom == false)
return $this->ret;

$this->root = $this->dom->documentElement;

$this->ret[$this->root->nodeName] = $this->parse_node($this->root);

$this->encoding = '';
$matches = array();
if (preg_match('/<\?xml.*encoding="(.*?)"\?>/', $xml, $matches))
$this->encoding = $matches[1];


return $this->ret;
}

function get_encoding() {
return $this->encoding;
}


}

Usage :

Case 1:  If you are getting some data from API and you used CURL request how it look like


/* Include xml_parser.php */
include('xml_parser.php');
$url = 'YOUR API URL';
$paraData = array('key'=>'value');
$buildQuery = $url. "?" . http_build_query($paraData);

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => $buildQuery,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => array(),
CURLOPT_HTTPHEADER => array(
'apikey: ADD your Key',

),
));

/*Response will be stored in $response */
$response = curl_exec($curl);
curl_close($curl);

/* create object from xml_parser class that we included and pass the api response which is $response*/
$xmlobj = new xml_parser();
$parseXMLData = $xmlobj->parse($response);

/* Now print the data */
echo '<pre>';
print_r($parseXMLData);
echo '</pre>';

 

Case 2: If you are getting XML data from a file or you have already it in string format then

$xmlString = '<root><item>Hello</item><item>World</item></root>';
$xml = simplexml_load_string($xmlString);

/* create object from xml_parser class that we included and pass the api response which is $response*/
$xmlobj = new xml_parser();
$parseXMLData = $xmlobj->parse($xml);

/* Now print the data */
echo '<pre>';
print_r($parseXMLData);
echo '</pre>';

I hope everything is well explained and this Bonus function solves your issue. If you have still any issue please contact me, and I will help you.

Happy Coding!

Related Blog

Sign up for our newsletter to stay up to
date with tech news!