Introduction:
XML often serves as a vessel for structured data. However, wrangling XML data can be complex. This blog explores how to convert XML data into arrays using PHP.
Method 1: Leveraging SimpleXML
The simple approach to XML-to-array conversion lies in the power of PHP's SimpleXML
extension. This extension offers a seamless way to load and traverse XML data as objects, eventually transforming it into arrays.
$xmlString = '<data><item>Value 1</item><item>Value 2</item></data>';
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
$array = json_decode($json, true);
print_r($array);
Output:
Array
(
[item] => Array
(
[0] => Value 1
[1] => Value 2
)
)
Method 2: DOMDocument's Might
PHP's DOMDocument
class offers a dynamic solution for XML manipulation. By loading XML data into a document object, developers can traverse nodes, extract their values, and construct arrays.
$xmlString = '<data><item>Value 1</item><item>Value 2</item></data>';
$doc = new DOMDocument();
$doc->loadXML($xmlString);
$array = [];
foreach ($doc->getElementsByTagName('item') as $item) {
$array[] = $item->nodeValue;
}
print_r($array);
Output:
Array
(
[0] => Value 1
[1] => Value 2
)
Method 3: Crafting a Custom Recursive Function
When dealing with intricate XML structures, a custom recursive function can be a game-changer. This technique enables developers to navigate complex hierarchies and generate arrays with precision.
function xmlToArray($node) {
$array = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_ELEMENT_NODE) {
$array[$child->nodeName] = xmlToArray($child);
} elseif ($child->nodeType === XML_TEXT_NODE) {
$array = $child->nodeValue;
}
}
return $array;
}
$xmlString = '<data><item>Value 1</item><item>Value 2</item></data>';
$doc = new DOMDocument();
$doc->loadXML($xmlString);
$array = xmlToArray($doc->documentElement);
print_r($array);
Output:
Array
(
[item] => Array
(
[0] => Value 1
[1] => Value 2
)
)
Conclusion:
In this blog, we have discussed three distinct techniques to convert XML File to Array in PHP like using SimpleXML method
, DOMDocument method
, and using a custom recursive function.
Comments (0)