【问题标题】:php Dynmically format xml to php array [closed]php将xml动态格式化为php数组[关闭]
【发布时间】:2013-03-31 08:11:35
【问题描述】:

您好,我想知道是否有人知道可以将任何 xml 文件格式化为特定格式的数组的脚本或函数,例如拥有类似这样的 xml(但要长得多)

<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 基本上想循环遍历每个属性,检查它内部是否还有更多等等,然后基本上创建一个数组,这样它看起来像这样

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

依此类推,所以基本上它只会抓取具有值的元素并跳过那些没有值的元素,并且 xml 的某些部分可能比其他部分有更多的子元素,它应该全部抓取它们,如果有多个属性相同的名称将是一个自己的数组,每个数组都是其中的一个数组

希望任何人都可以帮忙。我主要尝试使用simplexml,但可以使用其他任何东西

【问题讨论】:

标签: php xml xml-parsing xml-serialization simplexml


【解决方案1】:

对于像您示例中的文档这样的简单文档,总是有这个 (dirty) 技巧:

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

working example

输出:

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

【讨论】:

  • 可能还会添加 - 空字符串和数组都将满足 empty() - 如果您确实需要删除所有没有值的节点,您可以在之后运行并 unset() 它们。
  • 这种方法的唯一问题是我得到了两个预览对象,而不是一个包含两者的数组
  • @Yevo 你确定......我的输出与你的问题中所需的输出非常匹配,除了 fold=>show_lines 存在?我只能看到一个二维数组的预览数组?
  • 您实际上是正确的,结果很好。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-05-19
  • 2019-12-09
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多