2010-10-20 38 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.... 
} 
相关问题