Question

I have an xml file like this:

<js>
<ba>
    <ea>
        <jd>
      <option>first sko</option>
      <option>second sko</option>
      <option>third sko</option>
      <option>fourth sko</option>
      <option>fifth sko</option>
        </jd>
    </ea>
</ba>
</js>

I want to retrieve the tag name of the grandparent tag (i.e. "ea") starting from each value of the "option" tag.

So to get two levels up from this tag I have tried:

$xmlItem = simplexml_load_file(thexmlfile.xml);

foreach ($xmlItem->xpath('//jd/option') as $juzg) {
$cid = $xmlItem->xpath("name(//*[*[option = '" . $juzg . "']])");

$item['cid'] = (string)$cid;
}

The result I get when I echo the $cid or the $item['cid'] is an "Array" for each loop.

I am looking for the full script that will go in place of:

$cid = $xmlItem->xpath("name(//*[*[option = '" . $juzg . "']])");

I will appreciate any guidance on this issue.

Was it helpful?

Solution

$xmlItem->xpath returns an Array, so if you do (string)$xmlItem->xpath() you will always get 'Array'

In your example you would have to iterate again over $cid or just select $cid[0], but I don't think getting the name of the parent like this will work.

Either do:

foreach ($xmlItem->xpath('//jd/option') as $juzg) {
    $cid = $xmlItem->xpath("//*[*[option = '".$juzg."']]");

    $item['cid'] = $cid[0]->getName();
}

However this only works if there isn't any other option element in your xml document with the same content, so rather than relying on the content of the element just select its parent nodes:

foreach ($xmlItem->xpath('//jd/option') as $juzg) {
    $cid = $juzg->xpath('../..');

    $item['cid'] = $cid[0]->getName();
}

Here you even can be sure that $cid will only have one object because you select a parent and an element will always have just one parent.

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