Home >Backend Development >PHP Tutorial >How Can I Get the Source URL of the First Image in an HTML Document?

How Can I Get the Source URL of the First Image in an HTML Document?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 05:25:18670browse

How Can I Get the Source URL of the First Image in an HTML Document?

Retrieving the Source URL of the First Image in HTML

When parsing HTML documents, it can be useful to extract specific information, such as the source URL of the first occurring image tag. Here's how to achieve this using various methods:

Using DOMDocument and DOMXPath

This method utilizes the DOMDocument and DOMXPath classes to parse the HTML document and retrieve the source URL:

$html = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); // "/images/image.jpg"

Using Compact DOMXPath Syntax

For those seeking a more concise solution:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

Using SimpleXML and XPath

A one-liner approach that employs SimpleXML and XPath:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

The above is the detailed content of How Can I Get the Source URL of the First Image in an HTML Document?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn