PHP获取网站标题、关键词与描述接口

PHP获取网站标题、关键词与描述接口

Hackeus
2022-10-16 / 0 评论 / 121 阅读 / 正在检测是否收录...

PHP如何获取网站标题、关键词与描述呢?

在网页采集过程中,我们需要获取一个网站的meta信息,如title、keywords、description等,但是如果用普通的正则匹配很容易出错。那么到底该如何写这个PHP的代码,这篇文章为你带来解决方法。

使用get_meta_tags函数获取meta信息

比如我们要获取 httpa://blog.hackeus.cn 这个网页的meta信息,可以直接使用php内置函数get_meta_tags获取,代码如下:

<?php  
    $meta_tags = get_meta_tags("httpa://blog.hackeus.cn/");
    print_r($meta_tags);
?>

运行结果:你会发现获取了网页的关键词与描述,但是发现缺少了网页的标题,原因是标题并不是meta标签,而是组成的,所以我们的完整代码应该如下:

/** 获取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;
}
0

评论

博主关闭了所有页面的评论