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
Release: 2024-12-10 00:42:13
Original
774 people have browsed it

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)");
Copy after login

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"));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template