What are the best practices for extracting specific elements like text content from HTML using PHP?

When extracting specific elements like text content from HTML using PHP, it is best practice to use a library like DOMDocument or Simple HTML DOM Parser. These libraries provide functions to parse HTML and navigate through the DOM structure to extract the desired elements.

// Example using DOMDocument
$html = '<html><body><h1>Hello, World!</h1></body></html>';
$doc = new DOMDocument();
$doc->loadHTML($html);

$heading = $doc->getElementsByTagName('h1')->item(0)->nodeValue;
echo $heading; // Output: Hello, World!