PHP provides the simplexml_load_string method to parse strings in XML format and return the SimpleXMLElement object. However, the general array is more suitable, so it will also be converted to a common array... PHP provides the simplexml_load_string method to parse strings in XML format and return SimpleXMLElement objects. However, arrays are more suitable for general purposes and therefore need to be converted to common arrays, this method works completely and supports multiple layers of SimpleXMLElement objects.
Two parameters are provided. The first parameter is the SimpleXMLElement object, and the second parameter is a Boolean value to control whether the final return value contains the root node. the code is as follows:
children()) { return (string)$xml; } $array = array(); foreach ($xml->children() as $element => $node) { $totalElement = count($xml->{$element}); if (!isset($array[$element])) { $array[$element] = ""; } // Has attributes if ($attributes = $node->attributes()) { $data = array( 'attributes' => array() , 'value' => (count($node) > 0) ? $this->__xmlToArr($node, false) : (string)$node ); foreach ($attributes as $attr => $value) { $data['attributes'][$attr] = (string)$value; } if ($totalElement > 1) { $array[$element][] = $data; } else { $array[$element] = $data; } // Just a value } else { if ($totalElement > 1) { $array[$element][] = $this->__xmlToArr($node, false); } else { $array[$element] = $this->__xmlToArr($node, false); } } } if ($root) { return array( $xml->getName() => $array ); } else { return $array; }}?>
Article link:
Save this article for favorites!