From: Adam Maccabee Trachtenberg
accessing the text node children of an element is akin to object properties ($foo->bar); the syntax of accessing attributes is akin to array elements ($foo['bar']).
Hmm... This is somewhat up-side-down language wise. Attributes are properties of a node and the node contains children like an array contains elements. But I guess we'll keep it that way for nesting sake ($foo->foo2->foo3 is so much nicer than $foo['foo2']['foo3']).
But let's take a look on how I'd use it (xml formatted for readability): $foo = simplexml_load_string(' <foo x:a="xa" y:a="ya"> ab <foo2>foo2a</foo2> cd <foo2>foo2b</foo2> ef <foo3> foo3 <foo4>foo4</foo4> foo3 </foo3> gh </foo>');
foreach ($foo as $node) => foo2a foo2b foo3 foreach ($foo->foo2 as $node) => foo2a foo2b foreach ($foo->foo3 as $node) => foo4 foreach ((array)$foo->foo3 as $node) => foo4 foreach ($foo->foo3->foo4 as $node) => nothing foreach ((array)$foo->foo3->foo4 as $node) => foo4
What seems wrong here is that to output nodes where there can be 0 to multiple instances I have to do something like:
if ($foo->$nodename)
{
if (is_array($foo->$nodename))
{
foreach ($foo->$nodename as $node)
echo "$node\n";
}
else
echo "{$foo->$nodename}\n";
}
else
echo "No node $nodename found\n";
$nodename = 'node1' => No node node1 found $nodename = 'node2' => foo2a foo2b $nodename = 'node3' => foo3
Attributes are handled associative arrays, so given an element with 2 attributes with the same name, but in different namespaces, it wont work: <foo a:bar="x" b:bar="y">
Right now foo['bar'] will be an array('x', 'y') in that case. We're losing the namespaces here but get the values. Simple or broken? Not sure.
Should only be direct descendants. One should be able to navigate the entire tree (elements/attributes) in a standard way without having to use xpath.
I agree. What about getChildren($level = 1) with $level=0 meaning all? This offers both functionalities while having a default we decide on.
As right now there is no easy (read non-xpath/xquery) way of getting the attributes hidden in the magic array of $foo I think getAttributes should be added too.
No other functions though. Should these be methods? I think so.
$foo = simplexml_load_string('<foo>ab<foo2>test</foo2>cd</foo>'); $ns = $foo->xsearch('child::text()');
> foreach ($ns as $node) > print "Node Value: ".$node."\n";
I would actually expect abcd but only once: Node Value: abcd
Concatenating all text parts _and_ returning them once for each part definitely seems wrong.
+1 on getChildren/getAttributes (function or method) -1 on more functions
I think it's quite usable this way and simple enough to use to earn the name SimpleXML.
- Chris
-- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php