Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

A simply way to extract title and other attributes from a image tag

David Carr

PHP & MySQL Tutorials

    There's times where you need to dynamically extract attributes from image tags such as extracting the image title, alt or source tags this is very easy to do, by making use of the DOMDocument class that's built into php:

    To start instantiate the DOMDocument

    $doc = new DOMDocument();

    Then load the element your interested in, in this case an image.

    $doc->loadHTML('<img src="images/myimage.png" alt="My cool image" title="My cool image" />');

    Next add the elements to an array, by passing the tag your interested in.

    $imageTags = $doc->getElementsByTagName('img');

    Next loop through all the attributes and add the attribute you want to a variable.

    foreach($imageTags as $tag) {
        $source = $tag->getAttribute('src');
        $alt = $tag->getAttribute('alt');
        $title = $tag->getAttribute('title');
    }

    To use any of the attributes src, alt or title is very easily done now by referencing the associated variable for title use $title and source use $source.

    Here's the full script:

    <?php
    //instantiate the DOMDocument
    $doc = new DOMDocument();
    //load the element your interested in
    $doc->loadHTML('<img src="images/myimage.png" alt="My cool image" title="My cool image" />');
    //add elements to an array
    $imageTags = $doc->getElementsByTagName('img');
    
    //loop through the attributes
    foreach($imageTags as $tag) {
        $source = $tag->getAttribute('src');
        $alt = $tag->getAttribute('alt');
        $title = $tag->getAttribute('title');
    }

     

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

    © 2009 - 2022 DC Blog. All code MIT license. All rights reserved.