How to convert XML file into array in PHP?
There are multiple methods to convert an XML file into an array in PHP. Here are three common methods:
Method 1: Using SimpleXML
SimpleXML is a PHP extension that allows us to easily manipulate XML data. We can use the simplexml_load_file()
function to load an XML file and convert it into a SimpleXMLElement object. We can then use the json_encode()
and json_decode()
functions to convert the SimpleXMLElement object into an array.
$xml = simplexml_load_file('file.xml');
$json = json_encode($xml);
$array = json_decode($json, true);
Method 2: Using DOMDocument
DOMDocument is a PHP class that allows us to create, manipulate, and parse XML documents. We can use the load()
method to load an XML file and convert it into a DOMDocument object. We can then use the getElementsByTagName()
method to get the elements we want and loop through them to build an array.
$xml = new DOMDocument();
$xml->load('file.xml');
$elements = $xml->getElementsByTagName('*');
$array = array();
foreach ($elements as $element) {
$array[$element->nodeName][] = $element->nodeValue;
}
Method 3: Using XMLReader
XMLReader is a PHP class that allows us to read XML data one node at a time. We can use the open()
method to open an XML file and the read()
method to read each node. We can then use the nodeType
property to determine the type of node and the name
and value
properties to get the node name and value.
$xml = new XMLReader();
$xml->open('file.xml');
$array = array();
while ($xml->read()) {
if ($xml->nodeType == XMLReader::ELEMENT) {
$name = $xml->name;
$value = $xml->readString();
if (isset($array[$name])) {
if (!is_array($array[$name])) {
$array[$name] = array($array[$name]);
}
$array[$name][] = $value;
} else {
$array[$name] = $value;
}
}
}
Note: These methods may produce slightly different array structures depending on the XML file's structure.