How to extract img src, title, and alt from HTML string in PHP

1 Answer

0 votes
$html = '<img src="/images/abc.jpg" title="image title" alt="image alt">';

$dom = new DOMDocument();
libxml_use_internal_errors(true); // Suppress warnings for malformed HTML
$dom->loadHTML($html);
libxml_clear_errors();

$images = $dom->getElementsByTagName('img');

foreach ($images as $img) {
    $src = $img->getAttribute('src');
    $imageName = basename($src);
    $title = $img->getAttribute('title');
    $alt = $img->getAttribute('alt');

    echo "Src: $src, \nImageName: $imageName, \nTitle: $title, \nAlt: $alt\n";
}




/*
run:

Src: /images/abc.jpg, 
ImageName: abc.jpg, 
Title: image title, 
Alt: image alt

*/

 



answered Jul 23, 2025 by avibootz

Related questions

1 answer 72 views
1 answer 231 views
1 answer 178 views
1 answer 217 views
217 views asked Nov 16, 2020 by avibootz
3 answers 322 views
322 views asked Nov 26, 2017 by avibootz
1 answer 175 views
...