php Dynmically format xml to php array [closed]

2019-09-02 08:14发布

问题:

Hi I was wondering if anyone knows a script or function that can format any xml file to a array in a specific format such as having a xml something like this (but much longer)

<data>
    <width>3.5</width>
    <height>2</height>
    <edge>.125</edge>
    <safe>.125</safe>
</data>

<fold>
    <show_lines></show_lines>
    <type>online</type>
</fold>

<preview>
    <name>testfile</name>
    <location>testurl.com</location>
</preview>

<preview>
    <name>myfile</name>
    <location>someurl.com</location>
    <special>frontandback</special>
</preview>

Id basically want to loop through each attribute check if there is more inside of it and so on and so on and basically create a array so it would look like so

$array = [data] (
    width=>3.5
    height=>2
    edge=>.125
    safe=>.125
)

[fold] (
    type=>online
)

[preview] (
    [0]=>(
        name=>testfile
        location=>testurl.com
    )
    [1]=>(
         name=>myfile
         location=>someurl.com
         special=>frontandback
    )
)

and so on so basically it will only grab the elements that have values and skip the ones that dont and some parts of the xml may have more children than the other part and it should grab them all and if there is multiple attributes with same name that would be a array of its own with each one being a array inside of it

Hope that makes sense can anyone help please. Im mainly trying to use simplexml but can use anythign else

回答1:

For simple documents like the one in your example there's always this (dirty) trick:

$arr = json_decode(json_encode(simplexml_load_string($xml)), 1);

working example

output:

Array (
    [data] => Array (
        [width]  => 3.5
        [height] => 2
        [edge]   => .125
        [safe]   => .125
    )
    [fold] => Array (
        [show_lines] => Array ()
        [type]       => online
    )
    [preview] => Array (
        [0] => Array (
                [name]     => testfile
                [location] => testurl.com
        )
        [1] => Array (
                [name]     => myfile
                [location] => someurl.com
                [special]  => frontandback
        )
    )
)