T
T
topalek2020-04-17 11:07:24
PHP
topalek, 2020-04-17 11:07:24

How to change tag attributes on output?

Good day to all. There is a blog. Content is retrieved from the database. The content contains pictures and some user made a lazy-load

<img class="main-image lazy-load img-responsive" src="/img/loading.svg" alt="ТОП 10: Рейтинг лучших вытяжных вентиляторов" data-src="/uploads/blog/main/thumb/top_950_500.jpg">

The task is to swap the values ​​of the "data-src" and "src" attributes before displaying them on the page. This is done for the bot to process images with normal URLs when scanning.
The difficulty lies in the fact that there are a lot of pictures in the text and not all of them have "data-src".
Please help, I've been scratching my head for two days now.

UPD: I tried to replace it with this function
function replaceImageDataSrc($content)
    {
        $dom = new DOMDocument();
        $dom->loadHTML($content);
        $images = $dom->getElementsByTagName('img');

        foreach ($images as $image) {
            $dataSrc = $image->getAttribute('data-src');
            $src     = $image->getAttribute('src');
            $image->setAttribute('src', $dataSrc);
            $image->setAttribute('data-src', $src);
        }

        return $dom->saveHTML();
    }

but it doesn't work, there are unclosed tags somewhere in the content and DOMDocument falls into an error.
Need another way

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question