3

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.