Using PHP, SimpleXML and the xpath() function, I want to select a child node, starting from a certain point.
Can you please help me? I know in this specific case I could use an expression starting with “//”, but I want to learn the right way of selecting a child node.
Thanks.
First try — fails with Undefined offset: 0 error
$navXmlObject = simplexml_load_file("main_navigation.xml");
$tmpObject = $navXmlObject->website->xpath('title[@lang="fr"]');
echo($tmpObject[0]["label"]);
Second try, adding a slash — also fails with the same error
$tmpObject = $navXmlObject->website->xpath('/title[@lang="fr"]');
XML file
<?xml version="1.0" encoding="UTF-8"?>
<root>
<website id="MainWeb">
<title lang="fr" label="Mon site Web" />
<title lang="en" label="My web site" />
<menuNodes>
<menuNode id="Home">
<menuNodeData lang="fr" label="Accueil" url="/fr/accueil/" />
<menuNodeData lang="en" label="Home" url="/en/home/" />
</menuNode>
<menuNode id="Prod">
<menuNodeData lang="fr" label="Produits" url="/fr/produits/" />
<menuNodeData lang="en" label="Products" url="/en/products/" />
<menuNode id="Shoe">
<menuNodeData lang="fr" label="Chaussures" url="/fr/produits/chaussures/" />
<menuNodeData lang="en" label="Shoes" url="/en/products/shoes/" />
</menuNode>
</menuNode>
<menuNode id="Biog">
<menuNodeData lang="fr" label="Biographie du fondateur" url="/fr/biographie/" />
<menuNodeData lang="en" label="Biography of founder" url="/en/biography/" />
</menuNode>
</menuNodes>
</website>
</root>
It is strongly advised that you upgrade to a recent stable build and enjoy all of the improvements that would come with it. Now that that’s over with, the reason why your code is not working is precisely because such an old version of SimpleXML does not behave exactly as you expect it to.
The context node for the queries is not where you expect it to be (compared to saner, later versions for example). For the sake of ease of understanding, in my opinion, it would be easier for you just to use an absolute XPath.
Some examples that will work in your PHP 5.0.5 (and do in current versions) are:
To throw a spanner in the works, here’s an example that is just silly (yet should work for you in 5.0.5):