hi,欢迎访问本站!
当前位置: 首页编程开发正文

PHP获取网页标题,关键词以及描述的方法

墨初 编程开发 847阅读

用php脚本代码写了一个获取某个网页中tdk的工具,详细点说就是通过一个网址来获取网页中的标题,关键字以及描述。

php 获取指定网址中的标题,关键字以及描述的方法

函数代码:

/**
 * @name 获取网页中的TDK
 * @param $url 一个远程的网址
 * 
 * @return array
 * https://73so.com
 */
function get_tdk($url) 
{ 
    $meta = array();
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
    $data = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    if($code != 200){
        return $meta;
    }    
    if (!empty($data)) {
         #Title
         preg_match('/<TITLE>([\w\W]*?)<\/TITLE>/si', $data, $matches);
         if (!empty($matches[1])) {
              $meta['title'] = $matches[1];
         }
        
         #Keywords
         preg_match('/<META\s+name="keywords"\s+content="([\w\W]*?)"/si', $data, $matches);         
         if (empty($matches[1])) {
              preg_match("/<META\s+name='keywords'\s+content='([\w\W]*?)'/si", $data, $matches);              
         }
         if (empty($matches[1])) {
              preg_match('/<META\s+content="([\w\W]*?)"\s+name="keywords"/si', $data, $matches);              
         }
         if (empty($matches[1])) {
              preg_match('/<META\s+http-equiv="keywords"\s+content="([\w\W]*?)"/si', $data, $matches);              
         }
         if (!empty($matches[1])) {
              $meta['keywords'] = $matches[1];
         }
        
         #Description
         preg_match('/<META\s+name="description"\s+content="([\w\W]*?)"/si', $data, $matches);         
         if (empty($matches[1])) {
              preg_match("/<META\s+name='description'\s+content='([\w\W]*?)'/si", $data, $matches);              
         }
         if (empty($matches[1])) {
              preg_match('/<META\s+content="([\w\W]*?)"\s+name="description"/si', $data, $matches);                        
         }
         if (empty($matches[1])) {
              preg_match('/<META\s+http-equiv="description"\s+content="([\w\W]*?)"/si', $data, $matches);              
         }
         if (!empty($matches[1])) {
              $meta['description'] = $matches[1];
         }
    }
    return $meta;
}

函数使用方法

print_r(get_tdk('https://www.73so.com/'));
// Array ( [title] => 73SO...... [keywords] => php教程,php.... [description] => 这是一个关于...... )
声明:无特别说明,转载请标明本文来源!
相关推荐