Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
$xml = new SimpleXMLElement($xmlstr);
$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode); 

Not sure if this is still useful to you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top