有没有办法使用 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
)
)
最佳答案
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"
}
}
如果您的书籍可能有嵌套元素,那么它会变得有点复杂。
关于php - 将 XML 转换为关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6733974/