Skip to content Skip to sidebar Skip to footer

Get The Title Of A Page/url

Using php or javascript I want to get the title of the page Any help encouraged

Solution 1:

Per marc's answer. you'll have to fetch your server side script to get the effect if using JavaScript

JavaScript: (this will only give you the title of your current page):

<script language="JavaScript">
     alert(document.title);
     document.title='YOUR TITLE HERE';  //to set title
</script>

Here is the php way to do it:

$url = "http://www.google.com";
$file = file_get_contents($url);

if(preg_match("/<title>(.+)<\/title>/i",$file,$result)
print "The title of $url is <b>$result[1]</b>";
else
print "The page doesn't have a title tag";

this is modified from a post i bookmark long ago to achive the same effect credit source


Solution 2:

You can't do this in Javascript. Javascript cannot fetch the contents of arbitrary links. It's a security issue - look up XSR (cross-site requests) as to why.

You'd have to use AJAX to have your Javascript call a script on your server. That server-side script could fetch the specified page and parse out the title, then return it to the client-side Javascript.


Post a Comment for "Get The Title Of A Page/url"