当前位置:Gxlcms > PHP教程 > php访问url的四种方式

php访问url的四种方式

时间:2021-07-01 10:21:17 帮助过:94人阅读

10.jpg

1.fopen方式

  1. //访问指定URL函数
  2. function access_url($url) {
  3. if ($url=='') return false;
  4. $fp = fopen($url, 'r') or exit('Open url faild!');
  5. if($fp){
  6. while(!feof($fp)) {
  7. $file.=fgets($fp)."";
  8. }
  9. fclose($fp);
  10. }
  11. return $file;
  12. }

推荐学习:PHP视频教程

2.file_get_contents方式(打开远程文件的时候会造成CPU飙升。file_get_contents其实也可以post)

  1. $content = file_get_contents("http://www.google.com");

3.curl方式

  1. function curl_file_get_contents($durl){
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, $durl);
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
  5. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
  6. $r = curl_exec($ch);
  7. curl_close($ch);
  8. return $r;
  9. }

4.fsockopen方式(只能获取网站主页信息,其他页面不可以)

  1. $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
  2. if (!$fp) {
  3. echo "$errstr ($errno)<br />\n";
  4. } else {
  5. $out="GET / HTTP/1.1\r\n";
  6. $out.="Host: www.example.com\r\n";
  7. $out.="Connection: Close\r\n\r\n";
  8. fwrite($fp, $out);
  9. while (!feof($fp)) {
  10. echo fgets($fp, 128);
  11. }
  12. fclose($fp);
  13. }

以上就是php访问url的四种方式的详细内容,更多请关注Gxlcms其它相关文章!

人气教程排行