Jump to content

[SOLVED] Fetching The Title Of An URL...


PHPNewbie55

Recommended Posts

I am trying to grab the title of an URL

 

Here is what I am trying...  But I can't grab the title.. just what is inbetween the <body> and </body> tags....

 

This code will grab what ever is inbetween the <span> and </span> tags....

<?php
$url = "http://www.anyurl-anywhere-online.com";
$data = file_get_contents("".$url."");
preg_match('/<span>.*?<\/span>/',$data, $matches);
$title = "".$matches['0']."";

print "".$title.""; 
?>

 

So why won't this grab the title..???

<?php
$url = "http://www.anyurl-anywhere-online.com";
$data = file_get_contents("".$url."");
preg_match('/<title>.*?<\/title>/',$data, $matches);
$title = "".$matches['0']."";

print "".$title.""; 
?>

Link to comment
https://forums.phpfreaks.com/topic/102081-solved-fetching-the-title-of-an-url/
Share on other sites

The problem is that it is working - it's just also matching the <title> tags. If you were to view the source of the above, you would find the title tags. Nothing is displayed because title tags don't display anything.

 

To grab just the title and not the tags too, use:

 

<?php
$url = "http://www.anyurl-anywhere-online.com";
$data = file_get_contents($url);
preg_match('/<title>(.*?)<\/title>/',$data, $matches);
$title = $matches[1];

print $title; 
?>

 

 

By the way, there's no need to put empty strings before all your variables.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.