1

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.

Phil
  • 157,677
  • 23
  • 242
  • 245
max13
  • 63
  • 2
  • 5
  • possible duplicate of [Access an element's parent with PHP's SimpleXML?](http://stackoverflow.com/questions/2174263/access-an-elements-parent-with-phps-simplexml) – Phil Mar 25 '14 at 03:28
  • The issue is that I am interested in getting the ancestor's node name starting form each child node value... Apparently what is shown in the other answer is how to go through node values... – max13 Mar 25 '14 at 04:48
  • Just use the technique described in the other answer to go up two levels from each ` – Phil Mar 25 '14 at 04:52

1 Answers1

1

$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.

Tobias Klevenz
  • 1,625
  • 11
  • 13
  • Finally got it working... I used the second choice... An elegant solution I should say... – max13 Mar 26 '14 at 04:30