Home >Backend Development >PHP Tutorial >How Can I Extract the Source Attribute of an Image from HTML?

How Can I Extract the Source Attribute of an Image from HTML?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 00:42:13772browse

How Can I Extract the Source Attribute of an Image from HTML?

Extracting Image Source from HTML

To retrieve the source attribute of the first occurring image tag in an HTML document, various methods can be employed. Let's explore these approaches:

Using DOM (Document Object Model):

// Load the HTML content into a DOMDocument
$html = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
$doc->loadHTML($html);

// Create a DOMXPath object
$xpath = new DOMXPath($doc);

// Evaluate the XPath expression to extract the src attribute
$src = $xpath->evaluate("string(//img/@src)");

The result is assigned to the variable $src, which stores the source attribute value, e.g., "/images/image.jpg".

Using SimpleXMLElement:

$html = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

This approach combines DOMDocument with SimpleXMLElement to extract the src attribute.

Remember that these methods extract the source attribute of the first matching image tag. If there are multiple images, modify the XPath expression accordingly to target a specific one.

The above is the detailed content of How Can I Extract the Source Attribute of an Image from HTML?. 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