Home  >  Article  >  Backend Development  >  How to Convert a SimpleXML Object to an Array in PHP?

How to Convert a SimpleXML Object to an Array in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 02:42:03896browse

How to Convert a SimpleXML Object to an Array in PHP?

Converting a SimpleXML Object to an Array

Question

How can I efficiently and robustly convert a SimpleXML Object to an array? The existing approach using the json_decode() and json_encode() functions seems hacky.

Answer

Consider using the xml2array function provided in the PHP manual:

<code class="php">function xml2array($xmlObject, $out = array())
{
    foreach ((array)$xmlObject as $index => $node)
        $out[$index] = (is_object($node)) ? xml2array($node) : $node;

    return $out;
}</code>

This function recursively converts the SimpleXML Object into an array, preserving its structure and values.

Note

However, it's important to note that converting XML to an array involves some data loss, as attributes are not preserved during the conversion. Therefore, if round-trip functionality (conversion back to XML) is required, consider using an alternative approach that retains attributes.

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

Statement:
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