php获取网页meta信息(包括title、keywords、description)的两种方法

在网页采集过程中,我们需要获取一个网站的meta信息,如title、keywords、description等,本文章向大家介绍两种方法获取网站的meta信息,第一种方法是使用get_meta_tags函数,第二种方法是使用正则表达式匹配的方法获取。

1:使用get_meta_tags函数获取meta信息
比如我们要获取http://www.taobao.com这个网页的meta信息,可以直接使用php内置函数get_meta_tags获取,代码如下:

<?php  
    $meta_tags = get_meta_tags("https://www.csdn.net/");
    print_r($meta_tags);
?>

 2:使用正则表达式获取meta信息
PHP代码如下:

$site = "http://www.ub07.com";
$content = get_sitemeta($site);
print_r($content);


/** 获取META信息 */
function get_sitemeta($url) {
    
     $data = file_get_contents($url);
         
     $meta = array();
     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;
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值