2
<contact:addr>
  <contact:street></contact:street>
  <contact:street></contact:street>
  <contact:street></contact:street>
  <contact:city></contact:city>
  <contact:pc></contact:pc>
  <contact:cc></contact:cc>
</contact:addr>

On the example above we can see that we do have three times the element street; Is there a way, by using simpleXML, to properly access, for example, the second street element?

Thanks in advance, MEM

MEM
  • 30,529
  • 42
  • 121
  • 191

1 Answers1

5

The element reference in SimpleXML can be accessed as an array (since it is an iterator), meaning that $root->element[1] will return the second element with name "element" under the root. (and [0] will return the first, as shown in the SimpleXML examples in the PHP manual.)

You can iterate over all the elements using foreach($root->element as ..)

helios
  • 13,574
  • 2
  • 45
  • 55
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • @Gordon: Sir with 32135 reputation... I do believe that THAT is a tricky comment. I will have a look into the above. @fiskfisk thanks for the relation between the fact SimpleXML and iterator. ;) Really appreciated. – MEM Sep 06 '10 at 16:14
  • @Gordon: I do have something like this: $xmlObj->command->create->children(self::OBJ_URI_CONTACT)->create->postalInfo->addr->street and it works with the namespaces. Will not: $xmlObj->command->create->children(self::OBJ_URI_CONTACT)->create->postalInfo->addr->street[0] work ? – MEM Sep 06 '10 at 16:19
  • @all - for my previous question - a boolean answer may suffice. :) – MEM Sep 06 '10 at 16:23
  • @MEM It should work this way, but I found SimpleXml to be quirky when it comes to namespace support, though I hear it has been greatly improved with recent versions of PHP. Just give it a try. – Gordon Sep 06 '10 at 16:30
  • @Gordon - Tested. Worked perfectly. ;) Yeah! :D Cheers. – MEM Sep 06 '10 at 16:53