开发者

Convert XML to Associative array

Is there a way to convert XML to array using Zend Framework and PHP? I have seen folks using SimpleXML to do this, but I wanted to know if there's a way through Zend Framework.

Sample XML, I wanted to convert to array would be:

<library>
    <book>
        <authorFirst>Mark</authorFirst>
        <authorLast>Twain</authorLast>
        <title>The Innocents Abroad</title>
    </book>
    <book>
        <authorFirst>Charles</authorFirst>
        <authorLast>Dickens&开发者_StackOverflowlt;/authorLast>
        <title>Oliver Twist</title>
    </book>
</library>

The converted array will look like this:

Array 
( 
        [0] => Array ( 
                      [authorFirst] => Mark 
                      [authorLast] => Twain
                      [title] => Innocents Abroad
                     )
        [1] => Array (
                      [authorFirst] => Charles 
                      [authorLast] => Dickens
                      [title] => Oliver Twist
                     )
)


ZF also uses SimpleXML. For your example:

$xml = simplexml_load_string($data);
$books = array();
foreach ($xml->books as $book) {
    $books[] = (array)$book;
}

var_dump($books) will then give you:

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

if your books may have nested elements then it gets a little more complicated.


If you look aty the source code of Zend_Config_XML, you'll see them using SimpleXML to do almost exactly that. My guess? They'd suggest you do the same.


Unfortunately, or thankfully depending on your point of view, Zend Framework does not have a set of classes for everything possible--as of now. You have to use plain php (like simpleXML or DOMDocument) for this task or implement your own Zend class.

Converting a XML file into a PHP array would be something that fits into Zend_Filter. Zend_Filter converts many things right now and others are under development but I don't see anything like XML in the queue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜