Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over an object and transform into an array type

Tags:

php

xml

I have an XML class that reads an XML file and allows for it to be accessed like this

<config>
    <directory>
        <mvc>
             <model>model</model>
        </mvc>
    </directory>
</config>

echo $xml->config->directory->mvc->model

(assuming the object has been passed to a variable $xml)

outputs

model

I want to turn each parent/child/value nodes into an array. So

echo $xmlArr['config']['directory']['mvc']['model']

echo's model

I was in the process of using a foreach loop set up, but then realized that if the XML file has deep level of nested nodes, then my foreach statements would only cover so many levels. The XML files are a dynamic variable that I cannot account for and would need a dynamic method to be able to recursively iterate through the nodes and append them as array index.

like image 801
Eli Avatar asked Sep 07 '26 08:09

Eli


2 Answers

in PHP you can use xml_parse_into_struct method to convert XML structure to arrays

Reference:

http://www.php.net/manual/en/function.xml-parse-into-struct.php

like image 79
Saket Patel Avatar answered Sep 09 '26 21:09

Saket Patel


You might have a look at php.net.

For each depth level you can create an array in your loop and after iterating append it to your main array.

like image 21
Isaac Jacob Troyer Avatar answered Sep 09 '26 23:09

Isaac Jacob Troyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!