I have this sample xml file:-
<products>
<product_id value="1">
<tab_id value="251">
<dist_region value="5" />
<dist_region value="10066" />
<dist_region value="10069" />
</tab_id>
</product_id>
</products>
I am trying to get tab_id
child element using XPath
and I want result in set of child elements.
My expected output is as follows:-
dist_region,dist_region,dist_region
MY XPATH:-
$tab = $product->xpath('//tab_id/*');
Can anyone suggest what is the XPath
to get child elements? Thanks.
Your XPath
should be based on specific condition like value
(if it is <tab_id id='256'>
then more readable)
$result = $product->query('//tab_id[@value=' . $id . ']/*');
and then loop through it like below
if($result->length){
foreach ($result as $item):
echo "Value: ".$item['value'];
echo "<hr>";
endforeach;
}
The xpath you tried works for me. So, Try the next code:
$sxml = new SimpleXMLElement($xml);
$xpath = $sxml->xpath('//tab_id/*');
$array = array();
foreach ($xpath as $child)
{
$array[] = $child->getName();
}
echo implode(',',$array);
It gives you your desire output: dist_region,dist_region,dist_region.
Been $xml
your XML file.