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 5.1.1 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.38, 7.0.0 - 7.0.33, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 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.1.0
Fatal error: fatal flex scanner internal error--end of buffer missed in /in/7nPfr on line 60
Process exited with code 255.
Output for 5.0.0 - 5.0.5
Fatal error: Call to undefined method DOMXPath::evaluate() in /in/7nPfr on line 34
Process exited with code 255.
Output for 4.4.3 - 4.4.9
Parse error: syntax error, unexpected '(', expecting '}' in /in/7nPfr on line 55
Process exited with code 255.
Output for 4.4.2
Parse error: syntax error, unexpected '(', expecting '}' in /in/7nPfr 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/7nPfr on line 55
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `'}'' in /in/7nPfr on line 55
Process exited with code 255.

preferences:
256.72 ms | 401 KiB | 423 Q