Jake
Jake

Reputation: 26117

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

Upvotes: 3

Views: 6151

Answers (3)

cwallenpoole
cwallenpoole

Reputation: 82028

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.

Upvotes: 2

Adrian World
Adrian World

Reputation: 3128

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.

Upvotes: 0

Tim Fountain
Tim Fountain

Reputation: 33148

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.

Upvotes: 6

Related Questions