简体   繁体   中英

DOMDocument select only outer elements

If I got a DOMDocument like this:

<div name="outer">
    <div name="inner"></div>
    <div name="inner"></div>
</div>
<div name="outer">
</div>
<div name="outer">
    <div name="inner"></div>
</div>

If I do $dom->getElementsByTagName('div') , I am going to get all 6 elements, including the inner ones.

How can I for example select the second outer div element? ( name is just to show what I mean, the elements don't have these propertys for real!)

Edit:

I know I could use xpath , but I am more likely looking for a solution without it as I am using only the DOMDocument functions in the rest of my code.

Use DOMXPath

$xpath = new DOMXPath($doc);
$entry = $xpath->query('/div[2]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM