views:

297

answers:

4

I am try to find if a certain node has siblings, and if it does, I would like to know what those siblings are.

Is this possible?

A: 

I think using xpath is your best bet here:

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

function get_all_siblings(SimpleXMLElement $node)
{
  return $node->xpath('preceding-sibling::* | following-sibling::*');
}

$xml = simplexml_load_string($string);

foreach (get_all_siblings($xml->to) as $e)
  echo $e->getName()."\n";    
?>

Results in:

title
from
body
konforce
Because of the way SimpleXML works, you cannot filter the context node using `($node != $e)` as this comparison will always be true, even when both variables represent the same node.
Josh Davis
I don't use SimpleXML enough to have realized that... I've updated my code with different xpath syntax (which I see you've already posted anyway) that makes the function basically irrelevant.
konforce
A: 
$xml = new SimpleXMLElement($xmlstr);
$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode); 

Not sure if this is still useful to you

Chris
+2  A: 

In order to select a node's siblings, you have to use the corresponding XPath axe. Here is how to select all a node's siblings (ignoring the node itself)

$siblings = $node->xpath('preceding-sibling::* | following-sibling::*');

That's all you have to do.

Josh Davis