2013-03-31 38 views
0

您好我不知道是否有人知道一个脚本或功能,它可以格式化特定格式的XML文件的阵列,例如具有XML像这样(但更长时间)PHP Dynmically格式的XML到PHP数组

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

标识基本上要通过每个循环属性检查,如果有更多的这里面等等等等,基本上创建一个阵列,它看起来像这样

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

等所以基本上它将只抓取具有值的元素,并跳过那些不要和som的元素在XML电子部件可以有更多的孩子比其他部分,它应该抓住所有这些,如果不存在具有相同名称的多个属性,这将是它自己的阵列,每一个是它的内部

希望一个数组这是有道理的任何人都可以帮忙。进出口主要是想利用SimpleXML的,但可以使用anythign其他

+0

这可以帮助你:http://outlandishideas.co.uk/blog/2012/0 8/xml-to-json/ – SoldierCorp

+0

是的,这是可能的。它需要被编程。它已被编程(使用搜索)。你有什么尝试?你在哪里碰到路障? – hakre

回答

1

对于简单的文件,像在您的示例中总是有这样(脏)招:

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

也可能会添加 - 空字符串和数组都会满足['empty()'](http://php.net/manual/en/function.empty.php) - 如果您确实需要删除没有值的所有节点之后可以运行并[[unset()'](http://php.net/manual/en/function.unset.php)。 – Emissary

+0

这种方法唯一的问题是,我得到两个预览对象,而不是一个两个阵列 – Yeak

+0

@Yevo你确定...我的输出非常符合你想问题的输出,除了fold => show_lines在场?我只能看到一个预览数组,它是一个2D数组? – Emissary