What is the best way to extract the SRC attribute from an img tag in PHP?
To extract the SRC attribute from an img tag in PHP, you can use the DOMDocument class to parse the HTML content and then access the src attribute of the img tag. This can be done by loading the HTML content into a DOMDocument object, querying for the img tag elements, and then retrieving the value of the src attribute for each img tag found.
// HTML content with img tag
$html = '<img src="image.jpg">';
// Create a new DOMDocument
$dom = new DOMDocument();
// Load the HTML content into the DOMDocument
$dom->loadHTML($html);
// Get all img tags
$images = $dom->getElementsByTagName('img');
// Loop through each img tag and extract the src attribute
foreach ($images as $image) {
$src = $image->getAttribute('src');
echo $src; // Output: image.jpg
}