2

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.

raw_orb
  • 183
  • 1
  • 12

4 Answers4

3

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.

Community
  • 1
  • 1
Christos
  • 53,228
  • 8
  • 76
  • 108
1

Just try this:

<script type="text/javascript">
 alert(document.title);
</script>
Priyank
  • 3,778
  • 3
  • 29
  • 48
1

@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;
?>
Community
  • 1
  • 1
Lupin
  • 1,225
  • 11
  • 17
0

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()

Amit Joki
  • 58,320
  • 7
  • 77
  • 95