Home » Php » php – getting several elements by tag name and checking elements tag in a loop echoing it

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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';
    }
}

Answer:

It is better to use the following way, because by using this code, you will not get any error if there is no “iframe” / “img” tag present in the object “$doc” (as you are perfectly checking the existence of any elements using the “count()” function):-

$doc->loadHTML($article_header);
$imgs = $doc->getElementsByTagName('img');
$iframes = $doc->getElementsByTagName('iframe');

if (count($imgs)) {
    foreach ($imgs as $img) {
        // Do some logic on "img" tag
    }
}

if (count($iframes)) {
    foreach ($iframes as $iframe) {
        // Do some logic on "iframe" tag
    }
}

Hope it helps.