php調用遠程url的六種方法

來源:互聯網
上載者:User

範例程式碼1: 用file_get_contents 以get方式擷取內容
   <?php
   $url='http://www.baidu.com/';
   $html=file_get_contents($url);
  //print_r($http_response_header);
  ec($html);
  printhr();
  printarr($http_response_header);
   printhr();
  ?>
  
    範例程式碼2: 用fopen開啟url, 以get方式擷取內容
  <?
  $fp=fopen($url,'r');
  printarr(stream_get_meta_data($fp));
   printhr();
  while(!feof($fp)){
        $result.=fgets($fp,1024);
  }
  echo"url body:   $result";
  printhr();
  fclose($fp);
  ?>
範例程式碼3:用file_get_contents函數,以post方式擷取url
  <?php
  $data=array('foo'=>'bar');
  $data=http_build_query($data);

  $opts=array(
    'http'=>array(
   'method'=>'POST',
   'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
    "Content-Length: ".strlen($data)."\r\n",
  'content'=>$data
  ),
  );
$context=stream_context_create($opts);
$html=file_get_contents('http://localhost/e/admin/test.html',false,$context);
echo$html;
?>
範例程式碼4:用fsockopen函數開啟url,以get方式擷取完整的資料,包括header和body
<?
functionget_url($url,$cookie=false){
$url=parse_url($url);
$query=$url[path]."?".$url[query];
ec("Query:".$query);
$fp=fsockopen($url[host],$url[port]?$url[port]:80,$errno,$errstr,30);
if(!$fp){
      returnfalse;
}else{
      $request="GET$queryHTTP/1.1\r\n";
      $request.="Host:$url[host]\r\n";
      $request.="Connection: Close\r\n";
      if($cookie)$request.="Cookie:  $cookie\n";
      $request.="\r\n";
      fwrite($fp,$request);
      while(!@feof($fp)){
        $result.=@fgets($fp,1024);
      }
      fclose($fp);
      return$result;
}
}
//擷取url的html部分,去掉header
functionGetUrlHTML($url,$cookie=false){
   $rowdata=get_url($url,$cookie);
   if($rowdata)
   {
       $body=stristr($rowdata,"\r\n\r\n");
       $body=substr($body,4,strlen($body));
       return$body;
   }
   returnfalse;
}
?>
範例程式碼5:用fsockopen函數開啟url,以POST方式擷取完整的資料,包括header和body
<?
functionHTTP_Post($URL,$data,$cookie,$referrer=""){
// parsing the given URL
$URL_Info=parse_url($URL);

// Building referrer
if($referrer=="")// if not given use this script. as referrer
$referrer="111";

// making string from $data
foreach($dataas$key=>$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);

// Find out which port is needed - if not given use standard (=80)
if(!isset($URL_Info["port"]))
$URL_Info["port"]=80;

// building POST-request:
$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
$request.="Host: ".$URL_Info["host"]."\n";
$request.="Referer:$referer\n";
$request.="Content-type: application/x-www-form-urlencoded\n";
$request.="Content-length: ".strlen($data_string)."\n";
$request.="Connection: close\n";
$request.="Cookie:  $cookie\n";
$request.="\n";
$request.=$data_string."\n";

$fp=fsockopen($URL_Info["host"],$URL_Info["port"]);
fputs($fp,$request);
while(!feof($fp)){
      $result.=fgets($fp,1024);
}
fclose($fp);
return$result;
}
printhr();
?>
範例程式碼6:使用curl庫,使用curl庫之前,你可能需要查看一下php.ini,查看是否已經開啟了curl擴充
<?
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.baidu.com/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>
關於curl庫:
curl官方網站http://curl.haxx.se/
curl 是使用URL文法的傳送檔案工具,支援FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE和LDAP。curl 支援SSL認證、HTTP POST、HTTP PUT 、FTP 上傳,kerberos、基於HTT格式的上傳、代理、cookie、使用者+口令證明、檔案傳送恢複、http代理通道和大量其他有用的技巧
<?
functionprintarr(array$arr)
{
   echo"<br> Row field count: ".count($arr)."<br>";
   foreach($arras$key=>$value)
   {    
           echo"$key=$value    <br>";
   }
}
?>
======================================================
PHP抓取遠程網站資料的代碼
現在可能還有很多程式愛好者都會遇到同樣的疑問,就是要如何像搜尋引擎那樣去抓取別人網站的HTML代碼,然後把代碼收集整理成為自己有用的資料!今天就等我介紹一些簡單例子吧.

Ⅰ.抓取遠程網頁標題的例子:
以下是程式碼片段:
<?php
/*
+-------------------------------------------------------------
+抓取網頁標題的代碼,直接拷貝本程式碼片段,另存新檔.php檔案執行即可.
+-------------------------------------------------------------
*/

error_reporting(7);
$file = fopen ("http://www.dnsing.com/", "r");
if (!$file) {
echo "<font color=red>Unable to open remote file.</font>\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
if (eregi ("<title>(.*)</title>", $line, $out)) {
$title = $out[1];
echo "".$title."";
break;
}
}
fclose($file);

//End
?>
Ⅱ.抓取遠程網頁HTML代碼的例子:

以下是程式碼片段:
<? php
/*
+----------------
+DNSing Sprider
+----------------
*/

$fp = fsockopen("www.dnsing.com", 80, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)<br/>\n";
} else {
   $out = "GET / HTTP/1.1\r\n";
   $out .= "Host:www.dnsing.com\r\n";
   $out .= "Connection: Close \r\n\r\n";
   fputs($fp, $out);
   while (!feof($fp)) {
     echo fgets($fp, 128);
   }
   fclose($fp);
}
//End
?>
以上兩個程式碼片段都直接Copy回去運行就知道效果了,上面的例子只是抓取網頁資料的雛形,要使其更適合自己的使用,情況有各異.所以,在此各位程式愛好者自己好好研究一下吧.

===============================

稍微有點意義的函數是:get_content_by_socket(), get_url(), get_content_url(), get_content_object 幾個函數,也許能夠給你點什麼想法。
<?php

//擷取所有內容url儲存到檔案
function get_index($save_file, $prefix="index_"){
     $count = 68;
     $i = 1;
     if (file_exists($save_file)) @unlink($save_file);
     $fp = fopen($save_file, "a+") or die("Open ". $save_file ." failed");
     while($i<$count){
         $url = $prefix . $i .".htm";
         echo "Get ". $url ."...";
         $url_str = get_content_url(get_url($url));
         echo " OK\n";
         fwrite($fp, $url_str);
         ++$i;
     }
     fclose($fp);
}

//擷取目標多媒體對象
function get_object($url_file, $save_file, $split="|--:**:--|"){
     if (!file_exists($url_file)) die($url_file ." not exist");
     $file_arr = file($url_file);
     if (!is_array($file_arr) || empty($file_arr)) die($url_file ." not content");
     $url_arr = array_unique($file_arr);
     if (file_exists($save_file)) @unlink($save_file);
     $fp = fopen($save_file, "a+") or die("Open save file ". $save_file ." failed");
     foreach($url_arr as $url){
         if (empty($url)) continue;
         echo "Get ". $url ."...";
         $html_str = get_url($url);
         echo $html_str;
         echo $url;
         exit;
         $obj_str = get_content_object($html_str);
         echo " OK\n";
         fwrite($fp, $obj_str);
     }
     fclose($fp);
}

//遍曆目錄擷取檔案內容
function get_dir($save_file, $dir){
     $dp = opendir($dir);
     if (file_exists($save_file)) @unlink($save_file);
     $fp = fopen($save_file, "a+") or die("Open save file ". $save_file ." failed");
     while(($file = readdir($dp)) != false){
         if ($file!="." && $file!=".."){
             echo "Read file ". $file ."...";
             $file_content = file_get_contents($dir . $file);
             $obj_str = get_content_object($file_content);
             echo " OK\n";
             fwrite($fp, $obj_str);
         }
     }
     fclose($fp);
}

//擷取指定url內容
function get_url($url){
     $reg = '/^http:\/\/[^\/].+$/';
     if (!preg_match($reg, $url)) die($url ." invalid");
     $fp = fopen($url, "r") or die("Open url: ". $url ." failed.");
     while($fc = fread($fp, 8192)){
         $content .= $fc;
     }
     fclose($fp);
     if (empty($content)){
         die("Get url: ". $url ." content failed.");
     }
     return $content;
}

//使用socket擷取指定網頁
function get_content_by_socket($url, $host){
     $fp = fsockopen($host, 80) or die("Open ". $url ." failed");
     $header = "GET /".$url ." HTTP/1.1\r\n";
     $header .= "Accept: */*\r\n";
     $header .= "Accept-Language: zh-cn\r\n";
     $header .= "Accept-Encoding: gzip, deflate\r\n";
     $header .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; InfoPath.1; .NET CLR 2.0.50727)\r\n";
     $header .= "Host: ". $host ."\r\n";
     $header .= "Connection: Keep-Alive\r\n";
     //$header .= "Cookie: cnzz02=2; rtime=1; ltime=1148456424859; cnzz_eid=56601755-\r\n\r\n";
     $header .= "Connection: Close\r\n\r\n";

     fwrite($fp, $header);
     while (!feof($fp)) {
         $contents .= fgets($fp, 8192);
     }
     fclose($fp);
     return $contents;
}

//擷取指定內容裡的url
function get_content_url($host_url, $file_contents){

     //$reg = '/^(#|javascript.*?|ftp:\/\/.+|http:\/\/.+|.*?href.*?|play.*?|index.*?|.*?asp)+$/i';
     //$reg = '/^(down.*?\.html|\d+_\d+\.htm.*?)$/i';
     $rex = "/([hH][rR][eE][Ff])\s*=\s*['\"]*([^>'\"\s]+)[\"'>]*\s*/i";
     $reg = '/^(down.*?\.html)$/i';
     preg_match_all ($rex, $file_contents, $r);
     $result = ""; //array();
     foreach($r as $c){
         if (is_array($c)){
             foreach($c as $d){
                 if (preg_match($reg, $d)){ $result .= $host_url . $d."\n"; }
             }
         }
     }
     return $result;
}

//擷取指定內容中的多媒體檔案
function get_content_object($str, $split="|--:**:--|"){    
     $regx = "/href\s*=\s*['\"]*([^>'\"\s]+)[\"'>]*\s*(<b>.*?<\/b>)/i";
     preg_match_all($regx, $str, $result);

     if (count($result) == 3){
         $result[2] = str_replace("<b>多媒體: ", "", $result[2]);
         $result[2] = str_replace("</b>", "", $result[2]);
         $result = $result[1][0] . $split .$result[2][0] . "\n";
     }
     return $result;
}

?>

======================================================

同一網域名稱對應多個IP時,PHP擷取遠程網頁內容的函數

fgc就是簡單的讀取過來,把一切操作封裝了
fopen也進行了一些封裝,但是需要你迴圈讀取得到所有資料。
fsockopen這是直板板的socket操作。如果僅僅是讀取一個html頁面,fgc更好。如果公司是通過防火牆上網,一 般的file_get_content函數就不行了。當然,通過一些socket操作,直接向proxy寫http請求也是可以的,但是比較麻煩。

如果你能確認檔案很小,可以任選以上兩種方式fopen ,join('',file($file));。比如,你只操作小於1k的檔案,那最好還是用file_get_contents吧。

如果確定檔案很大,或者不能確定檔案的大小,那就最好使用檔案流了。fopen一個1K的檔案和fopen一個1G的檔案沒什麼明顯的區別。內容長,就可以花更長的時間去讀,而不是讓指令碼死掉。

----------------------------------------------------http://www.phpcake.cn/archives/tag/fsockopenPHP擷取遠程網頁內容有多種方式,例如用內建的file_get_contents、fopen等函數。
 

<?php  

echo file_get_contents("http://blog.s135.com/abc.php");?>

 但是,在DNS輪詢等負載平衡中,同一網域名稱,可能對應多台伺服器,多個IP。假設blog.s135.com被DNS解析到 72.249.146.213、72.249.146.214、72.249.146.215三個IP,使用者每次訪問blog.s135.com,系統會根據負載平衡的相應演算法訪問其中的一台伺服器。

  上周做一個視頻項目時,就碰到這樣一類需求:需要依次訪問每台伺服器上的一個PHP介面程式(假設為abc.php),查詢這台伺服器的傳輸狀態。

  這時就不能直接用file_get_contents訪問http://blog.s135.com/abc.php了,因為它可能一直重複訪問某一台伺服器。

  而採用依次訪問http://72.249.146.213/abc.php、http://72.249.146.214/abc.php、http://72.249.146.215/abc.php的方法,在這三台伺服器上的Web Server配有多個虛擬機器主機時,也是不行的。

  通過設定本地hosts也不行,因為hosts不能設定多個IP對應同一個網域名稱。

  那就只有通過PHP和HTTP協議來實現:訪問abc.php時,在header頭中加上blog.s135.com網域名稱。於是,我寫了下面這個PHP函數:

<?php   

  1.  /************************ 
  2.  * 函數用途:同一網域名稱對應多個IP時,擷取指定伺服器的遠程網頁內容 
  3.  * 建立時間:2008-12-09 
  4.  * 建立人:張宴(blog.s135.com) 
  5.  * 參數說明: 
  6.  *    $ip   伺服器的IP地址 
  7.  *    $host   伺服器的host名稱 
  8.  *    $url   伺服器的URL地址(不含網域名稱) 
  9.  * 傳回值: 
  10.  *    擷取到的遠程網頁內容 
  11.  *    false   訪問遠程網頁失敗 
  12.  ************************/  
  13.  function HttpVisit($ip, $host, $url)   
  14.  {   
  15.      $errstr = '';   
  16.      $errno = '';   
  17.      $fp = fsockopen ($ip, 80, $errno, $errstr, 90);   
  18.      if (!$fp)   
  19.      {   
  20.           return false;   
  21.      }   
  22.      else  
  23.      {   
  24.          $out = "GET {$url} HTTP/1.1\r\n";   
  25.          $out .= "Host:{$host}\r\n";   
  26.          $out .= "Connection: close\r\n\r\n";   
  27.          fputs ($fp, $out);        
  28.   
  29.          while($line = fread($fp, 4096)){   
  30.             $response .= $line;   
  31.          }   
  32.          fclose( $fp );     
  33.   
  34.          //去掉Header頭資訊  
  35.          $pos = strpos($response, "\r\n\r\n");   
  36.          $response = substr($response, $pos + 4);     
  37.   
  38.          return $response;   
  39.      }   
  40.  }     
  41.   
  42.  //調用方法:  
  43.  $server_info1 = HttpVisit("72.249.146.213", "blog.s135.com", "/abc.php");   
  44.  $server_info2 = HttpVisit("72.249.146.214", "blog.s135.com", "/abc.php");   
  45.  $server_info3 = HttpVisit("72.249.146.215", "blog.s135.com", "/abc.php");   
  46.  ?>  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.