To create a PHP function that retrieves the title for the webpage of the URL passed to it, you can utilize several approaches. Here are three methods, each with its own advantages and potential drawbacks:
Method 1: Using file_get_contents and Regular Expressions
This method involves fetching the HTML content of the URL and then using regular expressions to extract the title. It’s straightforward but might not handle complex HTML structures well.
function get_title_by_regex($url) {
$str = file_get_contents($url);
if (strlen($str) > 0) {
$str = trim(preg_replace('/\s+/', ' ', $str)); // Supports line breaks inside <title>
preg_match("/\<title\>(.*?)\<\/title>/is", $str, $title); // Non-greedy match
return isset($title[2])? $title[2] : '';
}
return '';
}
// Example usage
echo get_title_by_regex("http://www.example.com");
Method 2: Using DOMDocument
This approach uses the DOMDocument class to load the HTML content and then navigates the DOM tree to find the title element. It’s more robust against different HTML structures but requires more code.
function get_title_by_dom($url) {
$html = file_get_contents($url);
$dom = new DOMDocument;
@$dom->loadHTML($html);
$title = $dom->getElementsByTagName('title')->item(0);
return $title? $title->nodeValue : '';
}
// Example usage
echo get_title_by_dom("http://www.example.com");
Method 3: Using get_meta_tags
This method leverages PHP’s built-in get_meta_tags function, which reads meta tags from the given URL. It’s simple and effective for titles defined within <meta name="title" content="..."> tags.
function get_title_by_meta_tags($url) {
$tags = get_meta_tags($url);
return array_key_exists('title', $tags)? $tags['title'] : '';
}
// Example usage
echo get_title_by_meta_tags("http://www.example.com");
Each of these methods has its use cases. The choice depends on the specific requirements of your project, such as the complexity of the HTML structure you’re dealing with and whether you prefer a simpler or more robust solution.
Further reading …
- https://laracasts.com/discuss/channels/general-discussion/how-to-fetch-title-from-htmlxml
- https://stackoverflow.com/questions/4348912/get-title-of-website-via-link
- https://wordpress.stackexchange.com/questions/211840/get-title-of-page-from-url
- https://www.php.net/manual/en/function.get-meta-tags.php
- https://bytes.com/topic/php/915894-how-do-you-grab-title-current-page
- https://w3guy.com/php-retrieve-web-page-titles-meta-tags/
- https://www.sitepoint.com/community/t/how-to-extract-page-title-and-meta-keywords-descriptions/340503
- https://generatepress.com/forums/topic/post-title-with-external-link/
- https://www.sitepoint.com/community/t/how-to-grab-meta-tags-off-of-a-page/271263 [10] https://www.w3docs.com/snippets/php/getting-title-and-meta-tags-from-external-website.html


Leave a Reply