在PHP中,我们可以使用递归函数来处理XML数据。下面是一个示例代码:
<?phpfunction parseXML($xml) { $result = []; foreach ($xml->children() as $child) { $result[$child->getName()] = is_object($child) ? parseXML($child) : (string)$child; } return $result;}$xmlString = '<root> <item1>Value 1</item1> <item2> <subitem1>Subvalue 1</subitem1> <subitem2>Subvalue 2</subitem2> </item2></root>';$xml = simplexml_load_string($xmlString);$data = parseXML($xml);print_r($data);在这个示例中,我们定义了一个名为parseXML的递归函数,该函数接收一个SimpleXMLElement对象作为参数,并将XML数据解析为一个关联数组。递归函数会遍历XML的每个子元素,并将其存储为关联数组的键值对。
然后,我们使用simplexml_load_string函数将XML字符串加载为SimpleXMLElement对象,并将其传递给parseXML函数。最后,我们打印解析后的数据。




