To convert a SimpleXMLElement object to a PHP array _php tutorial

Source: Internet
Author: User
PHP provides the Simplexml_load_string method to parse the XML format string and return the SimpleXMLElement object. However, the general array is more applicable, so there will be the need to convert to a normal array, this method of testing is fully effective, support SimpleXMLElement object Multi-layered nesting situation.

Provides two parameters, the first parameter is a SimpleXMLElement object, the second parameter is a Boolean value, and the final return value is controlled to include 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 (
' 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;
}

}

Source: Mango Elementary Station

http://www.bkjia.com/PHPjc/363778.html www.bkjia.com true http://www.bkjia.com/PHPjc/363778.html techarticle PHP provides the Simplexml_load_string method to parse the XML format string and return the SimpleXMLElement object. However, the general array is more applicable, so there will also be converted to PU ...

  • 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.