What are some common methods to extract the title of an HTML page in PHP?
To extract the title of an HTML page in PHP, you can use regular expressions or a DOM parser. Regular expressions can be used to match the title tag and extract the title text, while a DOM parser like SimpleXMLElement or DOMDocument can be used to parse the HTML and extract the title element.
// Using regular expressions to extract the title from an HTML page
$html = file_get_contents('https://www.example.com');
preg_match("/<title>(.*?)<\/title>/i", $html, $matches);
$title = isset($matches[1]) ? $matches[1] : 'Title not found';
echo $title;
```
```php
// Using DOMDocument to extract the title from an HTML page
$html = file_get_contents('https://www.example.com');
$dom = new DOMDocument();
$dom->loadHTML($html);
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue;
echo $title;
Keywords
Related Questions
- Are there alternative encryption libraries or methods in PHP that can be used if mcrypt is not available on the web hosting server?
- How can the cssID property be effectively utilized in PHP to avoid dirty hacks or inefficient solutions?
- What are the potential pitfalls of relying on a database entry to determine online status for registered users?