Convert SimpleXMLElement object to an array in php

Source: Internet
Author: User
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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.