Converts a SimpleXMLElement object to a PHP array. PHP provides the simplexml_load_string method to parse strings in XML format and return the SimpleXMLElement object. However, arrays are more suitable, so the simplexml_load_string method is also provided for PHP to parse strings in XML format and return SimpleXMLElement objects. However, the general array is more suitable, so there will also be the need to convert to a common array, this method test works completely, supports SimpleXMLElement object multi-layer nesting.
Two parameters are provided. The first parameter is the SimpleXMLElement object, and the second parameter is a Boolean value, which controls whether the final return value contains the root node.
Function xmlToArr ($ xml, $ root = true ){
If (! $ Xml-> 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 (
'Bubuckets' => array (),
'Value' => (count ($ node)> 0 )? $ This->__ xmlToArr ($ node, false): (string) $ node
);
Foreach ($ attributes as $ attr => $ value ){
$ Data ['bubuckets'] [$ 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;
}
}
Source: Mango Xiaozhan
The http://www.bkjia.com/PHPjc/363778.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/363778.htmlTechArticlePHP provides the simplexml_load_string method to parse strings in XML format and return SimpleXMLElement objects. However, the general array is more suitable, so it will also be converted to the general...