将XML转换为关联数组

3
有没有一种使用Zend Framework和PHP将XML转换为数组的方法?我看到有人使用SimpleXML来做到这一点,但我想知道是否有一种通过Zend Framework的方式。
我要转换为数组的示例XML如下:
<library>
    <book>
        <authorFirst>Mark</authorFirst>
        <authorLast>Twain</authorLast>
        <title>The Innocents Abroad</title>
    </book>
    <book>
        <authorFirst>Charles</authorFirst>
        <authorLast>Dickens</authorLast>
        <title>Oliver Twist</title>
    </book>
</library>

转换后的数组将会像这样:
Array 
( 
        [0] => Array ( 
                      [authorFirst] => Mark 
                      [authorLast] => Twain
                      [title] => Innocents Abroad
                     )
        [1] => Array (
                      [authorFirst] => Charles 
                      [authorLast] => Dickens
                      [title] => Oliver Twist
                     )
)
3个回答

6
ZF也使用SimpleXML。以您的示例为例:
$xml = simplexml_load_string($data);
$books = array();
foreach ($xml->books as $book) {
    $books[] = (array)$book;
}

var_dump($books) 将会给你以下结果:

array(2) {
  [0]=>
  array(3) {
    ["authorFirst"]=>
    string(4) "Mark"
    ["authorLast"]=>
    string(5) "Twain"
    ["title"]=>
    string(20) "The Innocents Abroad"
  }
  [1]=>
  array(3) {
    ["authorFirst"]=>
    string(7) "Charles"
    ["authorLast"]=>
    string(7) "Dickens"
    ["title"]=>
    string(12) "Oliver Twist"
  }
}

如果您的图书可能有嵌套元素,则会变得更加复杂。

2
如果你查看Zend_Config_XML源代码,你会发现他们使用SimpleXML来实现几乎相同的功能。我的猜测是,他们会建议你也这样做。

0

不幸的是,或者根据您的观点而定,Zend Framework目前并没有针对所有可能情况的一组类。您必须使用普通的php(例如simpleXML或DOMDocument)来完成此任务,或者实现自己的Zend类。

将XML文件转换为PHP数组是适合放入Zend_Filter中的内容。Zend_Filter目前可以转换许多内容,其他内容正在开发中,但我没有看到任何类似于XML 在队列中的东西。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接