3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?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.4.0 - 5.4.32
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.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.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.