3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * @link http://stackoverflow.com/questions/26293581/how-to-select-2nd-element-with-same-tag-using-dom-xpath/26324381#26324381 */ $buffer = <<<BUFFER <div class="fly"> <img src="a.png" class="badge"> <img class="aye" data-original="b.png" width="130" height="253" /> <div class="to"> <h4>Fly To The Moon</h4> <div class="clearfix"> <div class="the"> <h4>**Wow**</h4> </div> <div class="moon"> <h4>**Great**</h4> </div> </div> </div> </div> BUFFER; $doc = new DOMDocument(); $doc->loadHTML($buffer); $xpath = new DOMXPath($doc); /*** * example with iteration ***/ // all <div> tags with class="fly" $divs = $xpath->evaluate("//div[@class='fly']"); foreach ($divs as $div) { // the first data-original attribute of an <img> inside $div echo $xpath->evaluate("string(./img/@data-original)", $div), "<br/>\n"; // all <h4> tags anywhere inside the $div $h4s = $xpath->evaluate('.//h4[not(following-sibling::*//h4)]', $div); foreach ($h4s as $h4) { echo $h4->nodeValue, "<br/>\n"; } } echo "\n----------\n\n"; /*** * example with string evaluation ***/ echo <<<HTML {$xpath->evaluate("string(//div[@class='fly']/img/@data-original)")}<br/> {$xpath->evaluate("string(//div[@class='fly']//h4[not(following-sibling::*//h4)][1])")}<br/> {$xpath->evaluate("string(//div[@class='fly']//h4[not(following-sibling::*//h4)][2])")}<br/> <hr/> HTML;
Output for 7.3.16 - 7.3.33, 7.4.3 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
b.png<br/> **Wow**<br/> **Great**<br/> ---------- b.png<br/> **Wow**<br/> <br/> <hr/>
Output for 5.4.0 - 5.4.32, 7.2.29 - 7.2.33
Parse error: syntax error, unexpected end of file in /in/Se26V on line 59
Process exited with code 255.
Output for 5.1.0 - 5.1.1, 5.1.3 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29
Parse error: syntax error, unexpected $end in /in/Se26V on line 59
Process exited with code 255.
Output for 5.1.2
Parse error: syntax error, unexpected $end in /in/Se26V on line 60
Process exited with code 255.
Output for 5.0.0 - 5.0.5
Parse error: parse error, unexpected $ in /in/Se26V on line 59
Process exited with code 255.
Output for 4.4.3 - 4.4.9
Parse error: syntax error, unexpected '(', expecting '}' in /in/Se26V on line 55
Process exited with code 255.
Output for 4.4.2
Parse error: syntax error, unexpected '(', expecting '}' in /in/Se26V on line 56
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
Parse error: parse error, unexpected '(', expecting '}' in /in/Se26V on line 55
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `'}'' in /in/Se26V on line 55
Process exited with code 255.

preferences:
179.21 ms | 401 KiB | 255 Q