What is the best way to access the title of an HTML document using PHP without loading the entire document into a variable?

To access the title of an HTML document using PHP without loading the entire document into a variable, you can use the DOMDocument class to parse the HTML and extract the title tag. This approach allows you to efficiently retrieve the title without having to store the entire document in memory.

<?php
// Create a new DOMDocument instance
$doc = new DOMDocument();

// Load the HTML content from a file or URL
$doc->loadHTMLFile('example.html');

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

// Output the title
echo $title;
?>