php Dynmically format xml to php array [closed]

徘徊边缘 提交于 2020-01-17 05:26:27

问题


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
        )
    )
)


来源:https://stackoverflow.com/questions/15727639/php-dynmically-format-xml-to-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!