Is there a way to pass the path to a simplexml node as a variable? This is what I tried:
//set the path to the node in a variable
$comp = 'component->structuredBody->component';
echo count($xml->component->structuredBody->component); //=== 13
echo count($xml->$comp); //===0
echo count($xml->{$comp});//===0
What you need is XPath, and more specifically SimpleXML's
xpath()
method. Instead of traversing using PHP's->
operator, you would traverse using XPath's/
operator, but otherwise, could achieve exactly the effect you wanted:You might think that this could be simplified to
'component/structuredBody/component'
, but that would find all possible paths matching the expression - that is if there are multiplestructuredBody
elements, it will search all of them. That might actually be useful, but it is not equivalent to$xml->component->structuredBody->component
, which is actually shorthand for$xml->component[0]->structuredBody[0]->component
.A few things to note:
registerXPathNamespace()
.