1

I have this function to get title of a website:

function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
    preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
    return $title[1];
}
}

However, this function make my page took too much time to response. Someone tell me to get title by request header of the website only, which won't read the whole file, but I don't know how. Can anyone please tell me which code and function i should use to do this? Thank you very much.

Mee
  • 815
  • 5
  • 11
  • 21

3 Answers3

3

Using regex is not a good idea for HTML, use the DOM Parser instead

$html = new simple_html_dom();
$html->load_file('****'); //put url or filename  
$title = $html->find('title');
echo $title->plaintext;

or

// Create DOM from URL or file
$html = file_get_html('*****');

// Find all images 
foreach($html->find('title') as $element) 
       echo $element->src . '<br>';

Good read

  1. RegEx match open tags except XHTML self-contained tags
Community
  • 1
  • 1
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
  • It said: "Call to undefined function file_get_html()" or "Class 'simple_html_dom' not found". Should I simply copy those code in my php file and replace those ****? Is there anything else I should do? – Mee Dec 25 '12 at 05:33
  • @user1904449 download and include [PHP Simple HTML DOM Parser](http://sourceforge.net/projects/simplehtmldom/files/) – NullPoiиteя Dec 25 '12 at 05:39
  • Hi i know its late but this thread helped me http://www.idiotminds.com/get-any-website-page-title-from-url-in-php/ – Uahmed Jan 04 '14 at 22:55
0

Use jQuery Instead to get Title of your page

$(document).ready(function() {
    alert($("title").text());
});​

Demo : http://jsfiddle.net/WQNT8/1/

Code Spy
  • 9,626
  • 4
  • 66
  • 46
  • 1
    Thank you, dextor. But I want to get title of any website by inputting its url, not my page. – Mee Dec 25 '12 at 06:17
0

try this will work surely

include_once 'simple_html_dom.php';

$oHtml = str_get_html($url);
$Title = array_shift($oHtml->find('title'))->innertext;
$Description = array_shift($oHtml->find("meta[name='description']"))->content;
$keywords = array_shift($oHtml->find("meta[name='keywords']"))->content;
echo $title;
echo $Description;
echo $keywords;
Shailendra Sharma
  • 6,976
  • 2
  • 28
  • 48