Rumah  >  Artikel  >  pembangunan bahagian belakang  >  快速了解PHP抓取网页内容的技巧

快速了解PHP抓取网页内容的技巧

WBOY
WBOYasal
2016-07-25 08:45:521027semak imbas

如何才能正确的实现php抓取网页内容呢?这个问题对于接触PHP语言不久的朋友来说有些难办。课课家今天就为大家介绍了具体的解决办法。


  首先,在C\windows里的php.ini中我打开了extension=php_curl.dll的功能,然后也重启了apapche,以下是我写的PHP抓取网页内容之抓取百度中PHP的信息:

  

  //初始化curl

  $ch = curl_init() or die (curl_error());

  echo "测试一下";

  //设置URL参数

  curl_setopt($ch,CURLOPT_URL,"http: //http://www.baidu.com/s?wd=php");

  //要求CURL返回数据

  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

  //执行请求

  $result = curl_exec($ch) or die (curl_error());

  //取得返回的结果,并显示

  echo $result;

  echo curl_error($ch);

  //关闭CURL

  curl_close($ch);

  ?>

  可为什么PHP抓取网页内容后没反应呢?连测试的文字都没有,要是我把echo "测试一下";放到第一行就可以输出,我估计是curl_init()函数还没有运行!

  你看看PHP的phpinfo()中有没有CURL扩展支持!

  把php_curl.dll拷到c:\windows\和c:\windows\system32里面 重启apache之后再试试看

  不是php_curl.dll这个文件,是把php目录中的libeay32.dll,ssleay32.dll拷到c:\windows\system32里面 重启apache

  为了服务器安全着想,所以把allow_url_fopen关掉了。

  当服务器allow_url_fopen = Off 时,就不能用file_get_contents,只有设置ON时可以用。

  

  $getstr=file_get_contents("http://www. 163.com/weatherxml/54511.xml");

  $qx=explode("\"",strstr($getstr,"qx="));

  $wd=explode("\"",strstr($getstr,"wd="));

  $qximg=explode("\"",strstr($getstr,"qximg="));

  $qximg_=explode(",",$qximg[1]);

  echo "北京 ".$qx[1]."";

  echo $wd[1];*/

  //echo " ";

  ?>

  以下PHP抓取网页内容的范例是通curl_init函数来获取163天气预报

  把php.ini里( ;extension=php_curl.dll ) 前面的(;)去掉保存

  把php_curl.dll,libeay32.dll,ssleay32.dll拷到c:\windows\system32里,重启IIS即可,没有装apache

  

  //初始化curl

  $ch = curl_init() or die (curl_error());

  //设置URL参数

  curl_setopt($ch,CURLOPT_URL,"http: //http://www.163.com/weatherxml/54511.xml");

  //要求CURL返回数据

  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

  //执行请求

  $result = curl_exec($ch) or die (curl_error());

  //取得返回的结果,并显示

  //echo $result;

  // echo curl_error($ch);

  $qx=explode("\"",strstr($result,"qx="));

  $wd=explode("\"",strstr($result,"wd="));

  $qximg=explode("\"",strstr($result,"qximg="));

  $qximg_=explode(",",$qximg[1]);

  echo "北京 ".$qx[1]."";

  echo $wd[1];

  //关闭CURL

  curl_close($ch);

  ?>

  通过以上对PHP抓取网页内容的学习,大家可以自行实际操作一遍,加深对它的理解。相关更多资料:http://www.kokojia.com/s64/




Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php 类定义和类使用实例 Artikel seterusnya:那些年遇到的荒唐事