文章簡(jiǎn)單的介紹了php中file_get_contents和curl兩個(gè)函數(shù)用法,在不能使用file_get_contents時(shí)可以嘗試一下curl函數(shù),下面是file_get_contents和curl兩個(gè)函數(shù)同樣功能的不同寫(xiě)法.
file_get_contents函數(shù)的使用示例,代碼如下:
- <?php
- $file_contents = file_get_contents('http://www.companysz.com/');
- echo $file_contents;
- ?>
換成curl函數(shù)的使用示例,代碼如下:
- <?php
- $ch = curl_init();
- $timeout = 5;
- curl_setopt ($ch, CURLOPT_URL, 'http://www.companysz.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函數(shù)來(lái)判斷php是否支持一個(gè)函數(shù)可以輕松寫(xiě)出下面函數(shù),代碼如下:
- <?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;
- }
- ?>
其實(shí)上面的這個(gè)函數(shù)還有待商議,如果你的主機(jī)服務(wù)商把file_get_contents和curl都關(guān)閉了,上面的函數(shù)就會(huì)出現(xiàn)錯(cuò)誤.
新聞熱點(diǎn)
疑難解答