php抓取网页数据的技术要点
|
admin
2013年2月25日 23:46
本文热度 9496
|
php中一般都是去抓取网页数据?如想把http://mp3.baidu.com/ 歌曲500TOP把抓下来,如何实现?
该文章在 2013/2/25 23:46:42 编辑过
| |
全部评论1 |
|
admin
2013年2月25日 23:52
问题中提到需要用PHP实现,个人总结整理了一下,有以下几种常用的用php抓取网页中的内容的方法,供您参考。
1.使用file_get_contents
<?php $url = http://www.34ways.com; $contents = file_get_contents($url); //如果出现中文乱码使用下面代码 //$getcontent = iconv(gb2312, utf-8,$contents); echo $contents; ?>
2.使用curl
<?php $url = http://www.34ways.com; $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //在需要用户检测的网页里需要增加下面两行 //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); //curl_setopt($ch, CURLOPT_USERPWD, US_NAME.:.US_PWD); $contents = curl_exec($ch); curl_close($ch); echo $contents; ?>
3.使用fopen->fread->fclose
<?php $handle = fopen (http://www.34ways.com, rb); $contents = ; do $contents .= $data; } while(true); fclose ($handle); echo $contents; ?>
最后提醒几点:
1.使用file_get_contents和fopen必须空间开启allow_url_fopen。
方法:
编辑php.ini,设置allow_url_fopen =
On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。
2.使用curl必须空间开启curl。
方法:
windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。
该答案已被锁定,无法对其进行评论,编辑及投票。
评论 (1)
|