文章簡單的介紹了php中file_get_contents和curl兩個函數用法,在不能使用file_get_contents時可以嘗試一下curl函數,下面是file_get_contents和curl兩個函數同樣功能的不同寫法.
file_get_contents函數的使用示例,代碼如下:
- <?php
- $file_contents = file_get_contents('http://www.49028c.com/');
- echo $file_contents;
- ?>
換成curl函數的使用示例,代碼如下:
- <?php
- $ch = curl_init();
- $timeout = 5;
- curl_setopt ($ch, CURLOPT_URL, 'http://www.49028c.com');
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $file_contents = curl_exec($ch);
- curl_close($ch);
- echo $file_contents;
- ?>
利用function_exists函數來判斷php是否支持一個函數可以輕松寫出下面函數,代碼如下:
- <?php
- function vita_get_url_content($url) {
- if(function_exists('file_get_contents')) {
- $file_contents = file_get_contents($url);
- } else {
- $ch = curl_init();
- $timeout = 5;
- curl_setopt ($ch, CURLOPT_URL, $url);
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $file_contents = curl_exec($ch);
- curl_close($ch);
- }
- return $file_contents;
- }
- ?>
其實上面的這個函數還有待商議,如果你的主機服務商把file_get_contents和curl都關閉了,上面的函數就會出現錯誤.
新聞熱點
疑難解答