What is the best way to extract link and image URLs from HTML code using PHP?
To extract link and image URLs from HTML code using PHP, you can use the DOMDocument class to parse the HTML and then extract the URLs using XPath queries. By using XPath, you can easily target specific elements like links and images based on their attributes.
// HTML code to parse
$html = '<a href="https://example.com">Example Link</a><img src="image.jpg">';
// Create a new DOMDocument
$dom = new DOMDocument();
$dom->loadHTML($html);
// Create a new DOMXPath object
$xpath = new DOMXPath($dom);
// Extract link URLs
$links = $xpath->query('//a/@href');
foreach ($links as $link) {
echo $link->nodeValue . "\n";
}
// Extract image URLs
$images = $xpath->query('//img/@src');
foreach ($images as $image) {
echo $image->nodeValue . "\n";
}