【问题标题】:How to extract title from php file get contents? [duplicate]如何从php文件中提取标题获取内容? [复制]
【发布时间】:2019-07-12 02:33:07
【问题描述】:
    <?php


     $content=file_get_contents('example.com');

   // it would return html <head>..... 
  <title>Example.com</title>

我想从标题中提取 example.com

  $title=pick('<title>','</title>',$content);

   Echo $title;

它会显示 Example.com

【问题讨论】:

标签: php


【解决方案1】:

您可以使用 substr 对 HTML 内容进行子串化,并使用 stripos 来查找标题标签。
我在去掉标签的位置加7。

$html = file_get_contents('example.com');
$pos = stripos($html, "<title>")+7;
echo substr($html, $pos, stripos($html, "</title>")-$pos);

示例:
https://3v4l.org/qvC40

这假设页面上只有一个标题标签,如果有更多则它将获得第一个标题标签。

【讨论】:

    【解决方案2】:

    您可以使用 file_get_content() 代替 $string。

        $string = "<title>MY TITLE</title>";
    
        $pattern = "/<title>(.*?)<\/title>/";
    
        preg_match($pattern, $string, $matches);
    
        echo "RESULT : ".$matches[1];
    
    【解决方案3】:

    尝试使用 PHP 的 simple xml parser 读取标题节点。

    $xml = simplexml_load_string(file_get_contents('example.com'));
    echo $xml->head->title;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-03
      • 2017-11-19
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多