php_curl庫的基本應用講解
今天我們就以實例向大家講解php_curl庫的基本用法,加深大家對php_curl庫的理解程度,比如我們可以通過設置函數curl_setopt() 的不同參數來實現不同的效果等等一些強大的功能。
簡介
#t#你可能在你的編寫PHP腳本代碼中會遇到這樣的問題:怎么樣才能從其他站點獲取內容呢?這里有幾個解決方式;最簡單的就是在php中使用fopen()函數,但是fopen函數沒有足夠的參數來使用,比如當你想構建一個“網絡爬蟲”,想定義爬蟲的客戶端描述(IE,firefox),通過不同的請求方式來獲取內容,比如POST,GET;等等這些需求是不可能用fopen() 函數實現的。
為了解決我們上面提出的問題,我們可以使用PHP的擴展庫-Curl,這個擴展庫通常是默認在安裝包中的,你可以它來獲取其他站點的內容,也可以來干別的。
備注:這兩段代碼需要php_curl擴展庫的支持,查看phpinfo(),如果curl support enabled則表示支持curl庫。
1、Windows下的PHP開啟curl庫支持:
打開php.ini,將extension=php_curl.dll前的;號去掉。2、Linux下的PHP開啟curl庫支持:
編譯PHP時在./configure后加上 –with-curl
在這篇文章中,我們一起來看看如何使用curl庫,并看看它的其他用處,但是接下來,我們要從最基本的用法開始
基本用法:
第一步,我們通過函數curl_init()創(chuàng)建一個新的curl會話,代碼如下:
- <?php
- // create a new curl resource$ch = curl_init();?>
我們已經成功創(chuàng)建了一個curl會話,如果需要獲取一個URL的內容,那么接下的一步,傳遞一個URL給curl_setopt()函數,代碼:
- <?php
- // set URL and other appropriate options
- curl_setopt($ch, CURLOPT_URL, “http://www.google.com/”);
- ?>
做完上一步工作,curl的準備工作做完了,curl將會獲取URL站點的內容,并打印出來。代碼:
- <?php
- // grab URL and pass it to the browser
- curl_exec($ch);
- ?>
最后,關閉當前的curl會話
- <?php
- //close curl resource, and free up system resources
- curl_close($ch);
- ?>
下面我們來看看完成的實例代碼:
- <?php
- // create a new curl resource
- $ch = curl_init();
- // set URL and other appropriate options
- curl_setopt($ch, CURLOPT_URL, “http://www.google.nl/”);
- // grab URL and pass it to the browser
- curl_exec($ch);
- // close curl resource, and free up system resources
- curl_close($ch);
- ?>
我們剛剛把另外一個站點的內容,獲取過來以后自動輸出到瀏覽器,我們有沒有其他的方式組織獲取的信息,然后控制其輸出的內容呢?完全沒有問題,在curl_setopt()函數的參數中,如果希望獲得內容但不輸出,使用CURLOPT_RETURNTRANSFER 參數,并設為非0值/true!,完整代碼請看:
- <?php
- // create a new curl resource
- $ch = curl_init();
- // set URL and other appropriate options
- curl_setopt($ch, CURLOPT_URL, “http://www.google.nl/”);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // grab URL, and return output
- $output = curl_exec($ch);
- // close curl resource, and free up system resources
- curl_close($ch);
- // Replace ‘Google’ with ‘PHPit’
- $output = str_replace(’Google’, ‘PHPit’, $output);
- // Print output
- echo $output;
- ?>
在上面的2個php_curl庫實例中,你可能注意到通過設置函數curl_setopt() 的不同參數,可以獲得不同結果,這正是curl強大的原因。