How to get first image of html content with PHP

The best way of getting the image of html contents is using DOM to get the src attribute.

I see some source code on Stack Exchange(Stack Overflow) trying to solve the problem with parsing the HTML content with their own parser. Studying and building parser is a great thing however in general case using DOM is best option that can handle html elements.

I have used this function in one of my wordpress theme for Search Engine Optimization and webpage design.
function getFirstImage($string){
    $dom = new DOMDocument;
    $dom->loadHTML($string);
    $images = $dom->getElementsByTagName('img');
    foreach ($images as $image) {
        return $image->getAttribute('src');
    }
    return false;
}



No comments:

Post a Comment