在PHP中調用介面

來源:互聯網
上載者:User

標籤:ica   result   while   type   ras   bdc   min   errno   bst   

引用:http://zhidao.baidu.com/question/454935450.html&__bd_tkn__=67bd5d3a742a8b244e09a86fb8b824aa950c9efd8078338d51fed8133ea5c69d362ad36bb4bcda3b39bb3949f6bbe47087ac3af56e60b1f4e7eb60157c59f93b9e62adfd5e0f03de01252778a636bc0c4a739c050b5fbd8ed149437d742a3220cb647f3449c2aba89e0ef9accbdc8c0bc23026f14aa0

如:
http://localhost/operate.php?act=get_user_list&type=json

在這裡operate.php相當於一個介面,其中get_user_list 是一個API(擷取使用者列表),講求返回的資料類型為JSON格式。

你只需要在你PHP代碼中執行這條連結他就會返回。
GET方式的直接使用 
$file_contents = file_get_contents(‘http://localhost/operate.php?act=get_user_list&type=json‘) 

POST方式得用下面的(需要開啟PHP curl支援)。 
$url = ‘http://localhost/operate.php?act=get_user_list&type=json‘;
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt ( $ch, CURLOPT_POST, 1 ); //啟用POST提交
$file_contents = curl_exec ( $ch );
curl_close ( $ch );

 

 

 

 

方法1:用file_get_contents以get方式擷取內容 <?php $url=’http://www.zhoz.com/’; $html=file_get_contents($url); //print_r($http_response_header); ec($html); printhr(); printarr($http_response_header); printhr(); ?>  方法2:用fopen開啟url,以get方式擷取內容 我覺得這個方法比較常用。 <?php $fp=fopen($url,‘r’); printarr(stream_get_meta_data($fp)); printhr(); while(!feof($fp)){ $result.=fgets($fp,1024); } echo"urlbody:$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 <?php 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([email protected]($fp)){ [email protected]($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 <?php functionHTTP_Post($URL,$data,$cookie,$referrer=""){ //parsingthegivenURL $URL_Info=parse_url($URL); //Buildingreferrer if($referrer=="")//ifnotgivenusethisscriptasreferrer $referrer="111"; //makingstringfrom$data foreach($dataas$key=>$value) $values[]="$key=".urlencode($value); $data_string=implode("&",$values); //Findoutwhichportisneeded–ifnotgivenusestandard(=80) if(!isset($URL_Info["port"])) $URL_Info["port"]=80; //buildingPOST-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擴充 <?php $ch=curl_init(); $timeout=5; curl_setopt($ch,CURLOPT_URL,‘http://www.zhoz.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、HTTPHTPPSSCPSFTPTFTPTELNETDICTFILE和LDAP。curl支援SSL認證、HTTPPOST、HTTPPUT、FTP上傳,kerberos、基於HTT格式的上傳、代理、cookie、使用者+口令證明、檔案傳送恢複、http代理通道和大量其他有用的技巧,最近熱門的SNS中也用到這個方法,取得MSN上的好友名單等,應用還是挺多的。只不過需要組件支援,開啟方法我的技術圈中有說明:http://o.zhoz.com/ <?php functionprintarr(array$arr) { echo"
Rowfieldcount:".count($arr)."
"; foreach($arras$key=>$value) { echo"$key=$value
"; } } ?>    
 /**     * 類比post進行url請求     * @param string $url     * @param string $param     */    function request_post($url = ‘‘, $param = ‘‘) {        if (empty($url) || empty($param)) {            return false;        }                $postUrl = $url;        $curlPost = $param;        $ch = curl_init();//初始化curl        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定網頁        curl_setopt($ch, CURLOPT_HEADER, 0);//設定header        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結果為字串且輸出到螢幕上        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);        $data = curl_exec($ch);//運行curl        curl_close($ch);                return $data;    }

這是方法,

下面是具體的調用案例。

    function testAction(){        $url = ‘http://mobile.jschina.com.cn/jschina/register.php‘;        $post_data[‘appid‘]       = ‘10‘;        $post_data[‘appkey‘]      = ‘cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ‘;        $post_data[‘member_name‘] = ‘zsjs123‘;        $post_data[‘password‘]    = ‘123456‘;        $post_data[‘email‘]    = ‘[email protected]‘;        $o = "";        foreach ( $post_data as $k => $v )         {             $o.= "$k=" . urlencode( $v ). "&" ;        }        $post_data = substr($o,0,-1);        $res = $this->request_post($url, $post_data);               print_r($res);    }

這樣就提交請求,並且擷取請求結果了。一般返回的結果是json格式的。

這裡的post是拼接出來的。

 

也可以改造成下面的方式。

/**     * 類比post進行url請求     * @param string $url     * @param array $post_data     */    function request_post($url = ‘‘, $post_data = array()) {        if (empty($url) || empty($post_data)) {            return false;        }                $o = "";        foreach ( $post_data as $k => $v )         {             $o.= "$k=" . urlencode( $v ). "&" ;        }        $post_data = substr($o,0,-1);        $postUrl = $url;        $curlPost = $post_data;        $ch = curl_init();//初始化curl        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定網頁        curl_setopt($ch, CURLOPT_HEADER, 0);//設定header        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結果為字串且輸出到螢幕上        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);        $data = curl_exec($ch);//運行curl        curl_close($ch);                return $data;    }

將拼接也封裝了起來,這樣調用的時候就更簡潔了。

function testAction(){        $url = ‘http://mobile.jschina.com.cn/jschina/register.php‘;        $post_data[‘appid‘]       = ‘10‘;        $post_data[‘appkey‘]      = ‘cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ‘;        $post_data[‘member_name‘] = ‘zsjs124‘;        $post_data[‘password‘]    = ‘123456‘;        $post_data[‘email‘]    = ‘[email protected]‘;        //$post_data = array();        $res = $this->request_post($url, $post_data);               print_r($res);    }

在PHP中調用介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.