What is the recommended way to extract specific lines of HTML text using PHP?

When extracting specific lines of HTML text using PHP, one recommended way is to use the DOMDocument class to parse the HTML content and then access the desired elements using XPath queries. This allows for more precise selection of the required lines based on their structure and attributes within the HTML document.

// Load the HTML content into a DOMDocument object
$html = '<html><body><div class="content">Line 1</div><div class="content">Line 2</div><div class="content">Line 3</div></body></html>';
$doc = new DOMDocument();
$doc->loadHTML($html);

// Use XPath to select specific lines based on class name
$xpath = new DOMXPath($doc);
$lines = $xpath->query('//div[@class="content"]');

// Extract and output the text content of each selected line
foreach ($lines as $line) {
    echo $line->textContent . "\n";
}