Home > Backend Development > PHP Tutorial > How to Convert a SimpleXML Object to an Array Efficiently and Preserve Attributes?

How to Convert a SimpleXML Object to an Array Efficiently and Preserve Attributes?

Mary-Kate Olsen
Release: 2024-10-27 08:11:02
Original
323 people have browsed it

How to Convert a SimpleXML Object to an Array Efficiently and Preserve Attributes?

Converting a SimpleXML Object to an Array: A More Efficient Approach

Converting a SimpleXML object to an array can be useful for manipulating XML data more efficiently. However, the method described in the initial question, which involves encoding and decoding JSON, can be cumbersome. Here's an improved approach to achieve the same:

function xmlstring2array($string) {

$xml = simplexml_load_string($string);
return xml2array($xml);
Copy after login

}

function xml2array($xmlObject) {

foreach ((array) $xmlObject as $index => $node) {
    if (is_object($node)) {
        $out[$index] = xml2array($node);
    } else {
        $out[$index] = $node;
    }
}
return $out;
Copy after login

}

This revised function, xml2array(), recursively iterates through the SimpleXML object, converting nodes into arrays while preserving their structure. It avoids the JSON encoding and decoding overhead, making it more efficient and robust.

The original function lost attributes when converting XML to an array. However, you can preserve attributes by using SimpleXML's attributes() method within the loop of xml2array():

foreach ((array) $xmlObject as $index => $node) {

...
if (is_object($node)) {
    $out[$index] = xml2array($node);
} else if ($node instanceof SimpleXMLElement) {
    $attrs = $node->attributes();
    if (count($attrs) > 0) {
        $out[$index] = (array) $node;
        foreach ($attrs as $attrName => $attrValue) {
            $out[$index][$attrName] = (string) $attrValue;
        }
    } else {
        $out[$index] = (string) $node;
    }
}
...
Copy after login

}

By incorporating these improvements, you can convert SimpleXML objects to arrays more efficiently, preserving both structure and attributes.

The above is the detailed content of How to Convert a SimpleXML Object to an Array Efficiently and Preserve Attributes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template