HLJ 发布于
2018-08-09 15:29:16

PHP获取网页标题、描述和关键词的方法

这篇文章主要介绍了怎样通过PHP获取网页标题、描述和关键词的方法,分别使用了curl_init()、curl_setopt()、curl_exec()、curl_close()、preg_match()函数来实现,需要的朋友可以参考下
注:如果报错请 1. 找到c:\php\php.ini文件 2. 搜索到extension=php_curl.dll 后把前面的分号去掉
获取方法1:
<?php
$ch = curl_init("http://www.100sucai.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$title = preg_match('!<title>(.*?)</title>!i', $result, $matches) ? $matches[1] : 'No title found';
$description = preg_match('!<meta name="description" content="(.*?)" />!i',
$result, $matches) ? $matches[1] : 'No meta description found';
$keywords = preg_match('!<meta name="keywords" content="(.*?)" />!i',
$result, $matches) ? $matches[1] : 'No meta keywords found';

echo $title . '<br>';
echo $description . '<br>';
echo $keywords . '<br>';
//输出结果为:
//最大素材网站_素材psd_素材天下_素材图片_免费网页素材_100素材网
//第一素材网一流的素材网站,提供优质的图片素材和代码素材的素材天下素材网站。
//第一素材网为网站建设人员提供网页特效,flash素材,网页设计,网页模板,网页素材等100素材网。
//素材网,素材网站,素材天下,素材中国,psd素材,图片素材,网页素材,flash素材,w3cschool,100素材网
?>

获取方法2:
<?php
function file_get_contents_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
$html = file_get_contents_curl("http://100sucai.com");
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}
echo "Title: $title". '<br/><br/>';
echo "Description: $description". '<br/><br/>';
echo "Keywords: $keywords";
?>

文章来源:http://www.100sucai.com/code/1292.html
最后生成于 2023-06-18 18:29:10
此内容有帮助 ?
0