Is there any foolproof+resource efficient way to get the title of a page using javascript and php.
So far I've tried:
1) Getting the whole code of the page and then separating the title from it by using explode()
2) Using $_SERVER['SCRIPT_NAME']
So, I just wanted to know if there is any better way of doing this.

- 183
- 1
- 12
-
Sayinf the title you don't mean the tab's title? If you want this it is fairly easy. – Christos Jan 14 '15 at 09:17
-
Question is not clear about context, could you explain more about what you want achieve and code snippet. – Dileep Jan 14 '15 at 09:18
-
If you mean getting a remote page, then get its html and use a DOM parser to get the `
` (with php) – Brewal Jan 14 '15 at 09:18 -
possible duplicate of [How to get current html page title with javascript](http://stackoverflow.com/questions/9228947/how-to-get-current-html-page-title-with-javascript) – Kevin Jan 14 '15 at 09:19
-
@Rakshit are you searching for html page title? – Priyank Jan 14 '15 at 09:20
-
Yes, I want the current page's HTML page title – raw_orb Jan 14 '15 at 09:21
4 Answers
You could the title of the page using JavaScript
as simple as document.title
.
<script type="text/javascript">
var title = document.title;
</script>
If you want to get the title of the page using jQuery
, you could try this:
$(function(){
var title = $('title').text();
})
Update
The above can be applied, if you are the "owner" of the page. If you want to get the title
of a page given it's url
, there is a helpful link here, which addresses this problem.
Just try this:
<script type="text/javascript">
alert(document.title);
</script>

- 3,778
- 3
- 29
- 48
@Christos has supplied a helpful link for getting the title using file_get_content()
and the full url of the page.
There is another approach to this, using the PHP Output Buffering Control. In this approach you will start the PHP page with ob_start(); then have your HTML code and then flush the output. in this scenario you you will have all the HTML code in the PHP buffer and can work on it as you like using the same regular expression as suggested in the file_get_content()
answer.
<?php
$title = NULL; // will hold the page title
ob_start(); // start output control
?>
<!-- HTML PAGE CODE HERE -->
<html>
<head>
<title>Page title from tag</title>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Aenean commodo ligula eget dolor. Aenean massa . </p>
</body>
</html>
<?php
// find the title in the buffer using ob_get_contents
if (preg_match('{<title[^>]*>(.*?)<\/title[ ]*>}i', ob_get_contents(), $matches)) {
$title = $matches[1];
}
// flush the buffer to screen
ob_end_flush();
// work with the title variable - check first if null
echo '<hr/>'.$title;
?>
title
property of document
object is what you need.
var title = document.title;
If you are using jQuery to bring in another page, you could do on it, $(data).find('title').text()

- 58,320
- 7
- 77
- 95