0

Possible Duplicate:
Parse XML sequentially in PHP

I want to be able to iterate through a SimpleXMLElementObject using PHP. However, I want to be able to do it without knowing the tag names in advance - I want a general solution that can be used as a discovery mechanism for the object's key names. I've tried a bunch of 'foreach' type solutions but can't get it to work.

Example code:

$schema = new SimpleXMLElement("<activity></activity>");
$schema->addAttribute("default-currency","asdf");
$schema->addAttribute("last-updated-datetime","jkl;");
$schema->addChild('title', 'example title');

print_r($schema) gives:

SimpleXMLElement Object ( 
    [@attributes] => Array ( 
        [default-currency] => asdf 
        [last- updated-datetime] => jkl; 
        ) 
    [title] => example title 
) 

Thanks

Community
  • 1
  • 1
Owen
  • 1,652
  • 2
  • 20
  • 24

1 Answers1

0

use getName function of SimpleXMLElement it will give you tag name

http://www.php.net/manual/en/simplexmlelement.getname.php

example

$sxe = new SimpleXMLElement("xml file");

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
    echo $child->getName() . "\n";
}
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
  • and how does `getName` help in iterating the DOM tree? – Gordon Oct 02 '12 at 12:51
  • @Gordon he has to do with `foreach` loop. – Yogesh Suthar Oct 02 '12 at 12:54
  • Right, but the OP - quoting - *"tried a bunch of 'foreach' type solutions but can't get it to work."* - your solution wont work either because it will only iterate the direct children of the root element and not the entire DOM tree. – Gordon Oct 02 '12 at 12:54
  • @Gordon because ha hasn't used `getName` function. – Yogesh Suthar Oct 02 '12 at 12:55
  • No because the OP doesnt know how to traverse the DOM tree. And your solution does not show him/her how to do it either. – Gordon Oct 02 '12 at 12:56
  • it will work when he used his logic with `getName` and `count`. – Yogesh Suthar Oct 02 '12 at 12:57
  • No, it won't. Your solution only works for `` but not for `` or any other DOM tree nested deeper than one level. – Gordon Oct 02 '12 at 12:58
  • I believe the solution could work for nested objects if used recursively? However, it's only discovering child elements (e.g. "title"). Ideally what I need is to discover the array "@attributes" as well. – Owen Oct 02 '12 at 17:02
  • Ok, sorry, looked at the object reference and $sxe->attributes() should do it. Thanks! I know this was a simple question in retrospect, but it really helped me understand the difference between working with sxe and working with normal classes. – Owen Oct 02 '12 at 19:26