JCZ
JCZ

Reputation: 430

Access SimpleXMLElement child elements as an array

How can I Access the SimpleXMLElement childs as an array?

SimpleXMLElement(9) {
 name => "John" (11)
 phone => array(2) [
    0 => "556 221 000" (19)
    1 => "312 555 110" (19)
 ]
}

According to this article http://www.sitepoint.com/parsing-xml-with-simplexml/ I should easily access it via

$sxElement->phone[0];

But then dump returns just:

SimpleXMLElement(0)

I need to access this in a for cycle. Thanks.

Edit (XML example):

<company>
  <phonebook>
    <name>John</name>
    <phone>556 221 000</phone>
    <phone>312 555 110</phone>
  </phonebook>
</company>

I need to go thru my foreach on another object and attach the correct phone according to iterator value.

Upvotes: 2

Views: 3211

Answers (3)

SamV
SamV

Reputation: 7586

You have to cast the data to an array so try this out (it worked for me).

$el = new SimpleXMLElement(
    '<company>
      <phonebook>
        <name>John</name>
        <phone>556 221 000</phone>
        <phone>312 555 110</phone>
      </phonebook>
    </company>'
);

$array = (array) $el->phonebook->phone;

The output of this is an array ready for manipulation.

Array
(
    [0] => 556 221 000
    [1] => 312 555 110
)

Another method that will get the key as well.

foreach($sxElement->phone as $i => $value) {
    echo "{$i} : {$value}" . PHP_EOL;
}

Although this cannot be accessed by the outer loop.

Upvotes: 4

Mindastic
Mindastic

Reputation: 4121

Have you tried with:

$sxElement->phone[0]->__toString();

Hope that helps.

Regards,

Marcelo

Upvotes: 2

TecBrat
TecBrat

Reputation: 3729

One solution I have found when working with simpleXML when I want to work with arrays is to pass the whole thing into and out of json, using the "true" parameter in json_decode(). Then I have an associative array that is more what I'm accustomed to working with.

Upvotes: 1

Related Questions