2010-10-20 63 views
34
$xml_file = file_get_contents(SITE_PATH . 'cms/data.php'); 

問題是服務器禁用了URL文件訪問。我無法啓用它,它是一個託管的東西。替代file_get_contents?

所以問題是這樣的。 data.php文件生成xml代碼。

如何在不執行上述方法的情況下執行此操作並獲取xml數據?

可能嗎?

+0

是SITE_PATH一部分*您*網站?還是在別的地方? – VoteyDisciple 2010-10-20 15:56:20

+0

它是我的網站的一部分。 SITE_PATH ='http://mydomain.com/'; – JasonS 2010-10-20 15:57:26

+0

[cURL和allow_url_fopen被禁用時如何抓取網站]可能的重複(http://stackoverflow.com/questions/3880628/how-to-scrape-websites-when-curl-and-allow-url-fopen-is -disabled) – Gordon 2010-10-20 16:10:14

回答

96

使用cURL。此功能是file_get_contents的替代方法。

function url_get_contents ($Url) { 
    if (!function_exists('curl_init')){ 
     die('CURL is not installed!'); 
    } 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $Url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $output = curl_exec($ch); 
    curl_close($ch); 
    return $output; 
} 
+5

這個功能救了我。謝謝。 – 2014-02-26 21:42:36

+0

但仍然收到「CURL未安裝!」但是我啓用了php_curl和php_openssl擴展 – 2015-03-12 08:06:45

+0

「CURL未安裝」表示您需要安裝cURL。 現在這是一種罕見的情況,大多數系統都默認安裝它。大多數基於dpkg的發行版都提供了一個名爲* php5_curl *的包,它附帶了正確的依賴關係和配置指令。 – 2015-03-13 11:05:45

3

是的,如果你有URL封裝禁用,你應該使用套接字或,甚至更好,cURL庫。

如果它是您網站的一部分,那麼請使用文件系統路徑引用它,而不是網址。 /var/www/...,而不是http://domain.tld/...

1

如果你想從URL讀取生成的XML不file_get_contents(),那麼你可能會想看看cURL

1

如果您有它可用,使用curl是最好的選擇。

您可以通過執行phpinfo()並搜索卷頁來查看它是否啓用。

如果啓用,試試這個:

$curl_handle=curl_init(); 
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php'); 
$xml_file = curl_exec($curl_handle); 
curl_close($curl_handle); 
2

如果該文件是本地作爲您的評論對SITE_PATH表明,它非常簡單,只需要執行腳本,並使用緩存結果在一個變量output control functions

function print_xml_data_file() 
{ 
    include(XML_DATA_FILE_DIRECTORY . 'cms/data.php'); 
} 

function get_xml_data() 
{ 
    ob_start(); 
    print_xml_data_file(); 
    $xml_file = ob_get_contents(); 
    ob_end_clean(); 
    return $xml_file; 
} 

如果是遠程的很多別人說curl是要走的路。如果不存在,請嘗試socket_createfsockopen。如果沒有任何工作......改變你的主機提供商

5

你應該嘗試這樣的事情, 我這樣做我的項目,其後備系統

//function to get the remote data 
function url_get_contents ($url) { 
    if (function_exists('curl_exec')){ 
     $conn = curl_init($url); 
     curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true); 
     curl_setopt($conn, CURLOPT_FRESH_CONNECT, true); 
     curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1); 
     $url_get_contents_data = (curl_exec($conn)); 
     curl_close($conn); 
    }elseif(function_exists('file_get_contents')){ 
     $url_get_contents_data = file_get_contents($url); 
    }elseif(function_exists('fopen') && function_exists('stream_get_contents')){ 
     $handle = fopen ($url, "r"); 
     $url_get_contents_data = stream_get_contents($handle); 
    }else{ 
     $url_get_contents_data = false; 
    } 
return $url_get_contents_data; 
} 

再後來,你可以像這樣

$data = url_get_contents("http://www.google.com"); 
if($data){ 
//Do Something.... 
}