PHP获取网页标题的3种实现方法代码实例
时间:2024-05-03 15:51:06
一、推荐方法 CURL获取
<?php
$c = curl_init();
$url = 'www.jb51.net';
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($c);
curl_close($c);
$pos = strpos($data,'utf-8');
if($pos===false){$data = iconv("gbk","utf-8",$data);}
preg_match("/<title>(.*)<\/title>/i",$data, $title);
echo $title[1];
?>
二、使用file()函数
<?php
$lines_array = file('https://www.jb51.net/');
$lines_string = implode('', $lines_array);
$pos = strpos($lines_string,'utf-8');
if($pos===false){$lines_string = iconv("gbk","utf-8",$lines_string);}
eregi("<title>(.*)</title>", $lines_string, $title);
echo $title[1];
?>
三、使用file_get_contents
<?php
$content=file_get_contents("https://www.jb51.net/");
$pos = strpos($content,'utf-8');
if($pos===false){$content = iconv("gbk","utf-8",$content);}
$postb=strpos($content,'<title>')+7;
$poste=strpos($content,'</title>');
$length=$poste-$postb;
echo substr($content,$postb,$length);
?>
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python如何查看微信消息撤回
![](https://img.aspxhome.com/file/2023/1/117961_0s.png)
python Popen 获取输出,等待运行完成示例
数据库中聚簇索引与非聚簇索引的区别[图文]
修改数据库为多用户模式
python实现kNN算法
![](https://img.aspxhome.com/file/2023/1/78831_0s.png)
分享10个免费超棒的编程用等宽字体
![](https://img.aspxhome.com/file/2023/6/132506_0s.jpg)
在Recordset对象中查询记录的方法
超简单的Python HTTP服务
简述:我为什么选择Python而不是Matlab和R语言
![](https://img.aspxhome.com/file/2023/0/102980_0s.png)
python控制台打印log输出重复的解决方法
![](https://img.aspxhome.com/file/2023/8/105578_0s.jpg)
JavaScript 学习 - 提高篇
Pytorch使用MNIST数据集实现基础GAN和DCGAN详解
![](https://img.aspxhome.com/file/2023/3/72183_0s.jpg)
Vue+Antv F2实现层叠柱状图
![](https://img.aspxhome.com/file/2023/7/139817_0s.jpg)
Python 一行代码能实现丧心病狂的功能
![](https://img.aspxhome.com/file/2023/8/61428_0s.png)
Jupyter notebook 启动闪退问题的解决
![](https://img.aspxhome.com/file/2023/9/82689_0s.jpg)
NopCommerce架构分析之(八)多语言支持
python如何将mat文件转为png
Python用SSH连接到网络设备
![](https://img.aspxhome.com/file/2023/1/89191_0s.png)
python使用tcp传输图片数据
![](https://img.aspxhome.com/file/2023/6/86616_0s.jpg)
Python3使用TCP编写一个简易的文件下载器功能
![](https://img.aspxhome.com/file/2023/3/118303_0s.png)