Tutorials, PHP & MySQL

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

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

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.