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

Susan Sarandon
Release: 2024-10-27 02:42:03
Original
895 people have browsed it

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!