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->str
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:
$comp = 'component[1]/structuredBody[1]/component';
echo count( $xml->xpath($comp) );
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 multiple structuredBody
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: