【问题标题】:How to get full page title efficiently如何有效地获取整页标题
【发布时间】:2015-01-14 09:16:16
【问题描述】:

有没有什么万无一失+资源有效的方法来使用 javascript 和 php 获取页面的标题。
到目前为止,我已经尝试过:
1) 获取页面的全部代码,然后使用explode()将标题与其分离
2) 使用$_SERVER['SCRIPT_NAME']

所以,我只是想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • 说标题你不是指标签的标题吗?如果你想要这个,这很容易。
  • 问题不清楚上下文,您能否详细解释一下您想要实现的目标和代码 sn-p。
  • 如果您的意思是获取远程页面,则获取其 html 并使用 DOM 解析器获取 <title>(使用 php)
  • @Rakshit 你在搜索 html 页面标题吗?

标签: javascript php title


【解决方案1】:

您可以使用JavaScriptdocument.title 一样简单的页面标题。

<script type="text/javascript">
    var title = document.title;
</script>

如果你想使用jQuery获取页面的标题,你可以试试这个:

$(function(){
    var title = $('title').text();
})

更新

如果您是页面的“所有者”,则可以应用上述内容。如果你想得到一个页面的title,因为它是url,有一个有用的链接here,它解决了这个问题。

【讨论】:

  • 有没有办法在php中也可以做到这一点(万无一失+高效)。
【解决方案2】:

试试这个:

<script type="text/javascript">
 alert(document.title);
</script>

【讨论】:

  • 感谢 js 解决方案,但我也想要一个 php 解决方案
  • 不,它只是一个定制的网站。
【解决方案3】:

@Christos 提供了一个helpful link 用于获取标题using file_get_content() 和页面的完整网址。

还有另一种方法,使用 PHP Output Buffering Control。在这种方法中,您将使用 ob_start() 启动 PHP 页面;然后拥有您的 HTML 代码,然后刷新输出。在这种情况下,您将拥有 PHP 缓冲区中的所有 HTML 代码,并且可以使用file_get_content() 答案中建议的相同正则表达式随意处理它。

<?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;
?>

【讨论】:

    【解决方案4】:

    document 对象的title 属性是您所需要的。

    var title = document.title;
    

    如果你使用 jQuery 来引入另一个页面,你可以这样做,$(data).find('title').text()

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      相关资源
      最近更新 更多