Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting several elements by tag name and checking elements tag in a loop echoing it

Tags:

dom

php

This is code sample that works

$doc->loadHTML($article_header);
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {

$imgs takes from $doc elements with tag name img and then I do some operations.

Now I want to getElementsByTagName > img OR iframe and then using $img check which element is this and echo if it is iframe or img.

Please modify my code if it is possible.

like image 280
David Avatar asked Oct 26 '11 17:10

David


1 Answers

You can use XPath on your DOMDocument as follows:

$doc->loadHTML($article_header);
$xpath = new DOMXpath($doc);

$imagesAndIframes = $xpath->query('//img | //iframe');

$length = $imagesAndIframes->length;
for ($i = 0; $i < $length; $i++) {
    $element = $imagesAndIframes->item($i);

    if ($element->tagName == 'img') {
        echo 'img';
    } else {
        echo 'iframe';
    }
}
like image 172
Jan-Henk Avatar answered Nov 15 '22 16:11

Jan-Henk