【问题标题】:PHP get site title from multiple URLsPHP 从多个 URL 获取站点标题
【发布时间】:2018-08-16 12:45:28
【问题描述】:

我有一堆链接。我需要从中提取标题。所以,我想让 textarea 粘贴链接和“获取标题”之类的按钮来提取标题。我做了一个函数来从一个 URL 中提取标题。它工作正常。我是 PHP 的新手,我不知道如何检测换行符以获取 url。谁能帮帮我?

这是我的代码

<?php
 function getTitle($url) {
 $data = file_get_contents($url);
$title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $data, $matches) ? $matches[1] : null;
return $title;
 }

 echo getTitle('http://example.com');
 ?>

【问题讨论】:

标签: php html regex dom


【解决方案1】:

请尝试此代码。当我们使用函数file_get_contents获取数据时,我们应该检查该数据的长度。

 function get_title($url){
      $str = file_get_contents($url);
      if(strlen($str)>0){
        $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
        preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
        return $title[1];
      }
    }
    //For Example:
 echo get_title("stackoverflow.com/"); 

输出是:

Stack Overflow - Where Developers Learn, Share, & Build Careers

【讨论】:

  • 这正是我现在所拥有的。我想粘贴多个 url,例如 example.com otherexample.com 等,然后为他们输出标题 example1 title otherexample title
【解决方案2】:

您可以为它们使用 preg_split()

$urls = $_REQUEST['urlArea'];

function getTitle($url) {
    $data = file_get_contents($url);
    $title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $data, $matches) ? $matches[1] : null;
    return $title;
}

// split by new-line character(\r\n or \r or \n)
$arr_url = preg_split('/\r\n|[\r\n]/', $urls);

foreach($arr_url as $url) {
    echo getTitle($url);
}

编辑:为完整代码添加的函数

【讨论】:

  • 嗯,它似乎可以工作,但它没有回应任何标题。我现在的代码 function getTitle($url) { $urls = $_REQUEST['urlArea']; $arr_url = preg_split('/\r\n|[\r\n]/', $urls); foreach($arr_url as $url) { echo getTitle($url); } }
  • 你递归调用了 getTitle() 函数。我用完整的代码编辑了我的答案
  • 见鬼!这就是我要找的。非常感谢!
  • @MMPL1 这是我的荣幸 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2014-05-25
相关资源
最近更新 更多