PHP 提供了 simplexml_load_string 方法用來解析 XML 格式的字符串,并返回 SimpleXMLElement 對象,不過一般數組是更為適用的,所以也會有轉換為普通數組的需求,這個方法測試完全奏效,支持 SimpleXMLElement 對象多層嵌套的情況.
提供兩個參數,第一個參數為 SimpleXMLElement 對象,第二個參數為布爾值,控制最終返回值是否包含根節點,代碼如下:
- 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(
- '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);
- }
- }
- }//開源代碼Vevb.com
- if ($root) {
- return array($xml->getName() => $array);
- } else {
- return $array;
- }
- }
新聞熱點
疑難解答