How can an array be built recursively from an XML file in PHP?
To build an array recursively from an XML file in PHP, you can use the SimpleXMLElement class to parse the XML file and convert it into an array. You can then iterate over the XML elements and build the array recursively by checking for child nodes and adding them as nested arrays.
function xmlToArray($xml) {
$array = [];
foreach ($xml->children() as $child) {
$name = $child->getName();
$data = (count($child->children()) === 0) ? (string) $child : xmlToArray($child);
if (!isset($array[$name])) {
$array[$name] = $data;
} else {
if (!is_array($array[$name]) || !array_key_exists(0, $array[$name])) {
$array[$name] = [$array[$name]];
}
$array[$name][] = $data;
}
}
return $array;
}
$xml = simplexml_load_file('data.xml');
$array = xmlToArray($xml);
print_r($array);
Related Questions
- How can regular expressions be used to extract specific date formats from a string in PHP?
- How can PHP developers effectively handle date formats retrieved from a database to display them in a desired format?
- What are the best practices for handling session management and user authentication in PHP applications?