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
- How can PHP developers ensure that date formatting functions are used correctly to avoid errors like those encountered in the forum thread?
- What are some potential pitfalls when using for loops to iterate through arrays in PHP?
- In what ways can referencing PHP documentation and understanding function structures help developers troubleshoot date formatting issues more effectively?