How can recursive functions be utilized to effectively parse XML data and extract variables in PHP?
Recursive functions can be utilized to effectively parse XML data in PHP by recursively traversing through the XML structure and extracting the desired variables. By defining a recursive function that can handle nested elements and attributes, you can extract the necessary data from the XML document.
function parseXML($xml) {
$result = [];
foreach ($xml->children() as $child) {
if ($child->count() > 0) {
$result[$child->getName()] = parseXML($child);
} else {
$result[$child->getName()] = (string) $child;
}
foreach ($child->attributes() as $key => $value) {
$result[$child->getName() . '_' . $key] = (string) $value;
}
}
return $result;
}
$xmlString = '<data><name>John</name><age>30</age><address city="New York">123 Main St</address></data>';
$xml = simplexml_load_string($xmlString);
$parsedData = parseXML($xml);
print_r($parsedData);