php访问url的四种方式
1.fopen方式
//访问指定URL函数
[php] view plain copy
- function access_url($url) {
- if ($url=='') return false;
- $fp = fopen($url, 'r') or exit('Open url faild!');
- if($fp){
- while(!feof($fp)) {
- $file.=fgets($fp)."";
- }
- fclose($fp);
- }
- return $file;
- }
2.file_get_contents方式(打开远程文件的时候会造成CPU飙升。file_get_contents其实也可以post)
[php] view plain copy
- $content = file_get_contents("http://www.google.com");
3.curl方式
[php] view plain copy
- function curl_file_get_contents($durl){
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $durl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
- curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
- $r = curl_exec($ch);
- curl_close($ch);
- return $r;
- }
4.fsockopen方式(只能获取网站主页信息,其他页面不可以)
[php] view plain copy
- $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
- if (!$fp) {
- echo "$errstr ($errno)<br /> ";
- } else {
- $out="GET / HTTP/1.1 ";
- $out.="Host: www.example.com ";
- $out.="Connection: Close ";
- fwrite($fp, $out);
- while (!feof($fp)) {
- echo fgets($fp, 128);
- }
- fclose($fp);
- }