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

David Carr

Tutorials PHP & MySQL

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 Your Logo Your Logo Your Logo

Become a sponsor

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

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.