先來看一下在php中建立curl請求的基本步驟:
(1)初始化
curl_init()
(2)設置變量
curl_setopt() 。最為重要。有一長串curl參數(shù)可供設置,它們能指定url請求的各個細節(jié)。要一次性全部看完并理解可能比較困難,所以今天我們只試一下那些更常用也更有用的選項。
(3)執(zhí)行并獲取結(jié)果
curl_exec()
(4)釋放curl句柄
curl_close()
下面就看一下具體的實現(xiàn):
1.post方式實現(xiàn)(模擬post請求,調(diào)用接口)
<?php$url = "http://192.168.147.131/index.php/adduser";//你要請求的地址$post_data = array( "uid" => "1111", "username" => "lunar", "nickname" => "吾獨望月",);$ch = curl_init();//初始化curl curl_setopt($ch,curlopt_url,$url);//抓取指定網(wǎng)頁curl_setopt($ch,curlopt_returntransfer,1);//要求結(jié)果為字符串并輸出到屏幕上curl_setopt($ch,curlopt_post,1);//post請求方式curl_setopt($ch,curlopt_postfields,$post_data);//post變量 $output = curl_exec($ch);//執(zhí)行并獲得html內(nèi)容curl_close($ch);//釋放curl句柄 print_r($output);2.get方式實現(xiàn)
<?php$url = "http://www.cnblogs.com/blogforly/";//你要請求的地址 $ch = curl_init();//初始化curl curl_setopt($ch,curlopt_url,$url);//抓取指定網(wǎng)頁curl_setopt($ch,curlopt_returntransfer,1);//要求結(jié)果為字符串并輸出到屏幕上curl_setopt($ch, curlopt_header, 0);//設置header $output = curl_exec($ch);//執(zhí)行并獲得html內(nèi)容curl_close($ch);//釋放curl句柄 print_r($output);相關學習推薦:php編程從入門到精通