How can PHP be used to extract specific information from HTML documents using tools like DOMDocument?

To extract specific information from HTML documents using tools like DOMDocument in PHP, you can load the HTML content into a DOMDocument object, navigate through the DOM structure to locate the desired elements, and then extract the information from those elements using methods like getElementById(), getElementsByTagName(), or getAttribute().

<?php
// HTML content to extract information from
$html = '<html><body><h1>Title</h1><p>Paragraph</p></body></html>';

// Load the HTML content into a DOMDocument object
$dom = new DOMDocument();
$dom->loadHTML($html);

// Get the title element
$title = $dom->getElementsByTagName('h1')->item(0)->nodeValue;

// Get the paragraph element
$paragraph = $dom->getElementsByTagName('p')->item(0)->nodeValue;

// Output the extracted information
echo "Title: $title\n";
echo "Paragraph: $paragraph\n";
?>