Extract Total Number of Image And Missing Alt Attribute using php

Extract Total Number of Image And Missing Alt Attribute using php

Here i will show you how can you extract total number of images from HTML content and find out missing alt attribute of the image using very simple code using php.

<?php
$html = '
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>Extract Total Number of Image And Missing Alt Attributte</title>
</head>
<body>
	<img src="test.png">
	<img src="test.jpg" alt="Testing">
	<img src="test.gif">
</body>
</html>';

$dom = new DOMDocument();
$dom->loadHTML($html);
$images = $dom->getElementsByTagName("img");
$allImagesCount = 0;
$altEmptyTag = 0;
foreach ($images as $image)
{
	if (!$image->hasAttribute("alt"))
	{
		$altEmptyTag++;
	}
	$allImagesCount++;
}
//echo $dom->saveHTML();
echo 'Total number of mages: '.$allImagesCount.'<br>';
echo 'Total number of mages missing alt attributes: '.$altEmptyTag.'<br>';
?>
Tags: How To Retrieve An Image Attachment’s Alt Text, How to get image title/alt attribute, How to extract img src, title and alt from html using php, HTML DOM images Collection, php get all images from url, php extract images from html, php html parser, simple html dom get attribute value, php script to download all images from url, simple_html_dom.php download, php image scraper , php preg_match get img src, wordpress get image alt text, the images on this page contain alt attributes, get image title attribute using php
About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.