Question

I have an array as follows:

array(
    'items' => array(
        'item' => array(
            (int) 0 => array(
                '@item' => '3-394-001068-00000'),
            (int) 1 => array(
                '@item' => '3-394-001069-00000'),
            )
     )
)

I am trying to extract all the 'item' entries to a new array.

Here is my code so far:

$xmlarray = Xml::toArray(Xml::build(WWW_ROOT .'files/itemsAll/'.$file));

            debug($xmlarray);
            $results = Hash::extract($xmlarray, '{n}.item');

            debug ($results);

but this returns only an empty array. Could someone maybe give me a hint where I'm going wrong?

thanks in advance

Was it helpful?

Solution

It isn't crystal clear from your question, but I assume this array

array(
    'items' => array(
        'item' => array(
            (int) 0 => array(
                '@item' => '3-394-001068-00000'),
            (int) 1 => array(
                '@item' => '3-394-001069-00000'),

is the result of your debug($xmlarray);, so we can rule out misslocation of a file (if I'm assuming wrong, do tell).

So, the hash is your problem.

See, according to docs, the {n} refers to "a numeric key", and "items" is clearly not. If you want to extract all "item" inside "items", it should be

Hash::extract($xmlarray, 'items.item');

and that will give you

array((int) 0 => array(
                '@item' => '3-394-001068-00000'),
            (int) 1 => array(
                '@item' => '3-394-001069-00000'),
/*etc*/

and, if you want to have a much compact array (don't know if you need the index associations), you could try

Hash::extract($xmlarray, 'items.item.{n}.@item');

and that'll get you

array('3-394-001068-00000', '3-394-001069-00000')

OTHER TIPS

Firstly, there are better ways to extract information from XML files than converting to an Array and then using Hash::extract(). Cake's XML library returns a SimpleXML object by default, so read up on the docs on that for how to extract information directly from the XML. Specifically, the xpath method may be of use to you. Your use might look something like this:

<?php
$xmlobj = Xml::build(WWW_ROOT .'files/itemsAll/'.$file);
$items = $xmlobj->xpath('/items/item');
?>

And then you can iterate through the $items object to do whatever you need to with the elements.

That said, if you're insistent on using Hash::extract(), looking at the dumped array, your item entries aren't under a numeric key, so {n} won't work to access them. You probably want either items.item, or if they can be under keys other than just 'items', {s}.item.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top