tags:

views:

169

answers:

2

I have a multi-dimensional multi-object array from a simplexml_import_dom() function call.

A slice of one section of the array:

[Price] => SimpleXMLElement Object
(
    [Prices] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [MType] => A
                            [PType] => R

This is causing me quite a bit of problems when trying to read nested objects. I have tried to loop through the array using multiple get_object_vars() but because the depth and location of the nested objects is continually changing I haven't been able to yield desirable results.

Does PHP contain a function that I haven't been able to find to convert a multi-dimensional multi-object array to a standard multi-dimensional array? Or has anyone solved this problem before?

Thanks for your help!

+1  A: 

Are you aware that these objects have functions that you can use? Try the following:

foreach ($simpleXmlObject->children() as $element) {
    echo $element->getName();
}
soulmerge
For some reason this never occurred to me to try. I will give this a try and post my results.
+1  A: 

The question is often asked, but there's a fundamental issue that has to be addressed on a case-by-case basis when converting a XML tree to an array, which makes an one-size-fits-all method impossible: how do you differentiate nodes from attributes?

For instance, how would you convert this XML to an array:

<node val="attr"><val>child</val></node>

Also, a node can have any number of children with the same name, which you can't emulate with an associative array.

Long story short, you'll have to cook up your own solution. Judging from your output, it would look something like this:

$arr = array();
foreach ($Price->Prices as $Prices)
{
    $tmp = array();

    foreach ($Prices->attributes() as $k => $v)
    {
        $tmp[$k] = (string) $v;
    }

    $arr[] = $tmp;
}

If it's not what you're looking for, please edit your question and add an example of the source document (XML) as well as the expected result (the array.)

Josh Davis