ItSolutionStuff.com

How to Extract Img SRC, Title and Alt from HTML in PHP?

By Hardik Savani • May 14, 2024
PHP

Hello Guys,

Today, I will let you know example of php get image tag from html. I explained simply about how to get src value from img tag in php. I would like to show you how to get img src from html in php. It's a simple example of how to find img src from html in php. So, let us see in detail an example.

In this example, we will use file_get_contents(), DOMDocument() and getAttribute() function to get img src value from html content in php. let's see the simple php example with output:

index.php

<?php

$url = "https://www.example.com";

$html = file_get_contents($url);

$doc = new DOMDocument();

@$doc->loadHTML($html);

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

foreach ($tags as $tag) {

echo "<br/><br/>SRC:" . $tag->getAttribute('src');

echo "<br/>ALT:" . $tag->getAttribute('alt');

echo "<br/>Title:" . $tag->getAttribute('title');

}

?>

Output:

I hope it can help you...

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Convert Array to XML in PHP?

Read Now →

How to Upgrade PHP Version from 8.2 to 8.3 in Ubuntu?

Read Now →

How to Install PHP 8.3 on Ubuntu 22.04?

Read Now →

How to Send Mail using PHPMailer in Laravel?

Read Now →

How to Get Duplicate Values from Array in PHP?

Read Now →

How to Check If a Value Exists in an Array in PHP?

Read Now →

PHP array_merge() Function Example

Read Now →

How to Remove Numeric Keys in PHP Array?

Read Now →

How to Remove String Values in PHP Array?

Read Now →

How to Get First 5 Elements of Array in PHP?

Read Now →

How to Get First 2 Elements of Array in PHP?

Read Now →

How to Get Last 2 Elements of Array in PHP?

Read Now →