摘要:文章簡(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函...
轉(zhuǎn)載請(qǐng)注明來(lái)源:php中file_get_contents和curl兩個(gè)函數(shù)用法

文章簡(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ù)的使用示例,代碼如下:

  1. <?php 
  2. $file_contents = file_get_contents('http://www.phpfensi.com/'); 
  3. echo $file_contents
  4. ?> 

換成curl函數(shù)的使用示例,代碼如下:

  1. <?php 
  2. $ch = curl_init(); 
  3. $timeout = 5; 
  4. curl_setopt ($ch, CURLOPT_URL, 'http://www.phpfensi.com'); 
  5. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  6. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
  7. $file_contents = curl_exec($ch); 
  8. curl_close($ch); 
  9. echo $file_contents; 
  10. ?> 

利用function_exists函數(shù)來(lái)判斷php是否支持一個(gè)函數(shù)可以輕松寫(xiě)出下面函數(shù),代碼如下:

  1. <?php 
  2.  
  3. function vita_get_url_content($url) { 
  4.  
  5. if(function_exists('file_get_contents')) { 
  6.  
  7. $file_contents = file_get_contents($url); 
  8.  
  9. else { 
  10.  
  11. $ch = curl_init(); 
  12.  
  13. $timeout = 5; 
  14.  
  15. curl_setopt ($ch, CURLOPT_URL, $url); 
  16.  
  17. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  18.  
  19. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
  20.  
  21. $file_contents = curl_exec($ch); 
  22.  
  23. curl_close($ch); 
  24.  
  25.  
  26. return $file_contents
  27.  
  28.  
  29. ?> 

其實(shí)上面的這個(gè)函數(shù)還有待商議,如果你的主機(jī)服務(wù)商把file_get_contents和curl都關(guān)閉了,上面的函數(shù)就會(huì)出現(xiàn)錯(cuò)誤. 轉(zhuǎn)載請(qǐng)注明來(lái)源:php中file_get_contents和curl兩個(gè)函數(shù)用法

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無(wú)需額外費(fèi)用,即可穩(wěn)步提升排名至首頁(yè)。歡迎體驗(yàn)最佳的哈爾濱網(wǎng)站建設(shè)。