Array & XML Conversion in PHP (Simple Approach)
Knowing the XML and PHP array conversion techniques is important when working with applications that allow data exchange. Learn different methods of converting XML to an array and an array to XML in a PHP application.

XML happens to be one of the popular formats modern PHP applications use for data exchange. This is when knowing the proper conversion of XML to an array and an array to XML in PHP applications becomes important. PHP arrays are used more often by developers to hold multiple values in a single variable and they are easy to work with. Whereas XML is used to store or share self-explanatory data which makes it a good option for data exchange. In this post, we will learn these conversion methods with example code snippets.
How to Convert XML to an Array in PHP?
This is often required when we need to process an API response in an XML format or to import XML data into a database. We can convert XML to an array in PHP with two different approaches. The first approach involves the use of simpleXML in combination with JSON encoding and decoding. The second approach involves the use of DOMDocument with recursion and gives us more control over XML attributes.
Method 1: Convert XML to an Array Using simpleXML
This is the simplest and most common approach involving simple steps with the use of simplexml_load_string() in combination with json_encode() and json_decode() functions. However, if the XML elements contain attributes, they will be lost at the second level and after in the tree.
- Prepare an XML string. The content usually comes from a file or an API response.
- Load the XML string using the
simplexml_load_string()method. - Encode and decode the loaded XML string using
json_encode()andjson_decode()methods.
//- Prepare static XML content as an example
$xml_string = <<<XML
<books>
<book id="1">
<title>Basic PHP</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book id="2">
<title>Advanced PHP</title>
<author>John Doe</author>
<price>29.99</price>
</book>
</books>
XML;
//- Load the XML string and JSON encode and decode
$xml = simplexml_load_string($xml_string);
$xml_to_array = json_decode(json_encode($xml), true);
//- The output of $xml_to_array
Array
(
[book] => Array
(
[0] => Array
(
[@attributes] => Array
(
[id] => 1
)
[title] => Basic PHP
[author] => John Doe
[price] => 29.99
)
[1] => Array
(
[@attributes] => Array
(
[id] => 2
)
[title] => Advanced PHP
[author] => John Doe
[price] => 29.99
)
)
)
The above code snippet will convert the XML to an array in PHP; however, if the elements <title>, <author> and <price> had their own attributes, they will be lost. This approach should work for simple XML conversion.
Method 2: Convert XML to an Array Using DOMDocument and Recursion
This approach requires a bit of manual handling but provides more control over conversion for a complex XML structure. This approach involves using the DOMDocument API with a custom recursive function to loop through all elements of XML, providing more control and access to elements, attributes, namespaces and text nodes. We will use the same XML as in the example above with an extra attribute "currency" for the <price> element.
- Prepare an XML document string and assign it to the
$xml_stringvariable. - Open a new
DOMDocumentand load the XML string into the document. - Use a recursive function,
parse_dom_node()and convert XML to an array.
//- Prepare static XML content as an example
$xml_string = <<<XML
<books>
<book id="1">
<title>Basic PHP</title>
<author>John Doe</author>
<price currency="usd">29.99</price>
</book>
<book id="2">
<title>Advanced PHP</title>
<author>John Doe</author>
<price currency="usd">29.99</price>
</book>
</books>
XML;
/***
* @param $node
* @return array|string
*/
function parse_dom_node($node): array|string
{
$output = [];
//- Get the attributes
if ($node->hasAttributes()) {
foreach ($node->attributes as $attribute) {
$output['@attributes'][$attribute->nodeName] = $attribute->nodeValue;
}
}
//- Get the child nodes
if ($node->hasChildNodes()) {
$children = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_TEXT_NODE) {
$text = trim($child->nodeValue);
if (!empty($text)) {
$output['@value'] = $text;
}
} elseif ($child->nodeType === XML_ELEMENT_NODE) {
$child_name = $child->nodeName;
$child_data = parse_dom_node($child);
if (!isset($children[$child_name])) {
$children[$child_name] = $child_data;
} else {
//- Multiple elements with same name to array
if (!is_array($children[$child_name]) || !isset($children[$child_name][0])) {
$children[$child_name] = [$children[$child_name]];
}
$children[$child_name][] = $child_data;
}
}
}
$output = array_merge($output, $children);
}
return $output;
}
//- Open a new DOMDocument & load the XML string to the document
$doc = new DOMDocument();
$doc->loadXML($xml_string);
//- Get the root element of the document
$root = $doc->documentElement;
//- Prepare an array of XML elements recursively
$xml_to_array = parse_dom_node($root);
//- The resulting array
Array
(
[book] => Array
(
[0] => Array
(
[@attributes] => Array
(
[id] => 1
)
[title] => Array
(
[@value] => Basic PHP
)
[author] => Array
(
[@value] => John Doe
)
[price] => Array
(
[@attributes] => Array
(
[currency] => usd
)
[@value] => 29.99
)
)
[1] => Array
(
[@attributes] => Array
(
[id] => 2
)
[title] => Array
(
[@value] => Advanced PHP
)
[author] => Array
(
[@value] => John Doe
)
[price] => Array
(
[@attributes] => Array
(
[currency] => usd
)
[@value] => 29.99
)
)
)
)
How to Convert an Array to XML in PHP?
PHP does not offer any built-in function that we can use to convert a PHP array to XML. So this step involves the use of DOMDocument and a recursive function to go through all elements of the array and prepare an XML document.
- Prepare an array of books and assign it to a variable
$books. - Write a recursive function
convert_array_to_xml()which accepts three parameters,$data,$doc, and$parentvariable. - Open a new
DOMDocumentwithformatOutputset totrue. - Create a root element books and assign the attribute
collection-namefor the indexed array. XML does not support numeric element names. - Append the root element to the document.
- Call the
convert_array_to_xml()function, providing it the required parameters. - Finally, print or save the prepared XML.
//- An array of books
$books = [
[
'@attributes' => [
'id' => 1
],
'title' => [
'@value' => 'Basic PHP'
],
'author' => [
'@value' => 'John Doe'
],
'price' => [
'@attributes' => [
'currency' => 'usd'
],
'@value' => 29.99
]
],
[
'@attributes' => [
'id' => 2
],
'title' => [
'@value' => 'Advanced PHP'
],
'author' => [
'@value' => 'John Doe'
],
'price' => [
'@attributes' => [
'currency' => 'usd'
],
'@value' => 29.99
]
],
];
/***
* @param $data
* @param $doc
* @param $parent
* @return mixed
*/
function convert_array_to_xml($data, &$doc, $parent = null): mixed
{
foreach ($data as $key => $value) {
if (is_numeric($key)) {
//- Assume numeric keys mean repeating elements
$key = $parent->getAttribute('collection-name') ?? 'item';
}
$element = $doc->createElement($key);
if ($parent) {
$parent->appendChild($element);
} else {
$doc->appendChild($element);
}
if (is_array($value)) {
if (isset($value['@attributes'])) {
foreach ($value['@attributes'] as $attribute_name => $attribute_value) {
$element->setAttribute($attribute_name, $attribute_value);
}
}
if (isset($value['@value'])) {
$element->appendChild($doc->createTextNode($value['@value']));
}
//- Recurse into other child elements
$children = array_diff_key($value, ['@attributes' => '', '@value' => '']);
if (!empty($children)) {
convert_array_to_xml($children, $doc, $element);
}
} else {
//- The scalar value
$element->appendChild($doc->createTextNode($value));
}
}
return $doc;
}
//- Open a new DOMDocument and set the formatOutput to true
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->formatOutput = true;
//- Add a root element i.e. books and set the collection name for the books indexed array
$root = $doc->createElement('books');
$root->setAttribute('collection-name', 'book');
$doc->appendChild($root);
//- Convert the array to XML recursively
$xml = convert_array_to_xml($books, $doc, $root);
echo $xml->saveXML();
We demonstrated different approaches to convert XML to an array and an array to XML in PHP. Knowing these conversion methods is useful for easier data manipulation and filtering. PHP makes it simple to work with XML and arrays with a few lines of code. The code can be further extended according to the complexity of the XML structure and the application's specific requirements.