How to extract img src, title, and alt from HTML using PHP?

Spread the love

Sometimes, we want to extract img src, title, and alt from HTML using PHP.

In this article, we’ll look at how to extract img src, title, and alt from HTML using PHP.

How to extract img src, title, and alt from HTML using PHP?

To extract img src, title, and alt from HTML using PHP, we can parse the HTML with the DOMDocument class.

For instance, we write

$url = "http://example.com";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

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

foreach ($tags as $tag) {
    echo $tag->getAttribute("src");
}

to call file_get_contents to get the HTML from the $url.

Then we create a new DOMDocument object and call loadHTML with the $html string.

And then we get the img element with getElementsByTagName.

Then we use the foreach loop to loop through the elements and call getAttribute to get the src attribute of each img element.

Conclusion

To extract img src, title, and alt from HTML using PHP, we can parse the HTML with the DOMDocument class.

Leave a Reply

Your email address will not be published.