Aristeidis Karavas
Aristeidis Karavas

Reputation: 1956

Simple XML find the parent on multiple levels above with PHP

I have an xml file that looks like this: (names are fictional)

<base>
 <subbase>
   <item>
     <childItem>
       <childItemLevel1>
          <childItemLevel2>Value 1 </childItemLevel2>
          <childItemLevel2>Value 2 </childItemLevel2>
          <childItemLevel2>Value 3 </childItemLevel2>
        </childItemLevel1>
        <childItemLevel1>
          <childItemLevel2>Value 10 </childItemLevel2>
          <childItemLevel2>Value 20 </childItemLevel2>
          <childItemLevel2>Value 30 </childItemLevel2>
        </childItemLevel1>
     </childItem>
   </item>
 </subbase>
</base>

I use SimpleXML and I can not figure out how I can get the parent on more than one level.

For example:

I am at the <childItemLevel2>Value 10</childItemLevel2>.

How can I get to the parent <item> and print it out?

Thanks in advance.

Upvotes: 0

Views: 490

Answers (1)

ThW
ThW

Reputation: 19512

With Xpath axes.

$base = new SimpleXMLElement($xml);

$child = $base->xpath('.//childItemLevel2[contains(., "Value 10")]')[0];

var_dump($child->asXml());

$parent = $child->xpath('ancestor::item[1]')[0];

var_dump($parent->asXml());

Output:

string(44) "<childItemLevel2>Value 10 </childItemLevel2>"
string(484) "<item>
     <childItem>
       <childItemLevel1>
          <childItemLevel2>Value 1 </childItemLevel2>
          <childItemLevel2>Value 2 </childItemLevel2>
          <childItemLevel2>Value 3 </childItemLevel2>
        </childItemLevel1>
        <childItemLevel1>
          <childItemLevel2>Value 10 </childItemLevel2>
          <childItemLevel2>Value 20 </childItemLevel2>
          <childItemLevel2>Value 30 </childItemLevel2>
        </childItemLevel1>
     </childItem>
   </item>"

ancestor is an axis that contains any node up the hierarchy to the document element node. ancestor::item will select any that is named item on this axis. ancestor::item[1] selects the first (nearest) from that list.

Upvotes: 1

Related Questions