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');
}

 

Copyright © 2006 - 2024 DC Blog - All rights reserved.