XML to PHP array

balandžio 10th, 2012

Some times when working in PHP you need a way to convert an XML document into a serializable array. If you ever tried to serialize() and then unserialize() a SimpleXML or DOMDocument object, you know what I’m talking about.

Assume the following XML snippet:

<tv>
<show name="The Simpsons">
<husband>Homer</husband>
<wife>Marge</wife>
<kid>Bart</kid>
<kid>Lisa</kid>
<kid>Maggie</kid>

</show>
</tv>

I found quick but little dirty way to do convert such axml document to an array, using type casting and JSON functions. After this i can ensure there are no exotic values that would cause problems when unserializing:

<?php
$a = json_decode(json_encode((array) simplexml_load_string($tv)),1);
?>

After this we get:

Array
(
    [show] => Array
        (
            [@attributes] => Array
                (
                    [name] => The Simpsons)
            [husband] => Homer
            [wife] => Marge
            [kid] => Array
                (
                    [0] => Bart
                    [1] => Lisa
                    [2] => Maggie
                )
        )
)

DONE!


Be Sociable, Share!

Leave a Reply