php – 为什么file_get_contents不起作用?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 为什么file_get_contents不起作用?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么file_get_contents对我不起作用?在下面的测试文件代码中,似乎我搜索过的所有人的示例都列出了此函数,但它永远不会被执行.这是网络托管服务的问题吗?有人可以在他们的服务器上测试这个代码只是为了看看地理编码数组输出是否实际打印成字符串?当然,我正在尝试将输出分配给变量,但此测试文件中没有输出….

<htML>
<head>        
<tITle>test File</title>
<script tyPE="text/javascript" src="http://maps.GOOGLE.COM/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&amp;sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
PRint '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

解决方法

检查 file_get_contents PHP Manual返回值.如果值为FALSE则无法读取文件.如果值为NULL,则禁用函数本身.

了解file_get_contents操作可能出现的问题,您必须启用错误报告并显示错误以实际读取它们.

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors',1);

您可以通过检查服务器上的INI值来获取有关呼叫失败原因的更多详细信息.直接影响file_get_contents函数一个值是allow_url_fopen.您可以通过运行以下代码来执行此操作.您应该注意,如果它报告不允许fopen,那么您必须要求您的提供商更改服务器上的此设置,以便任何需要此功能代码才能使用URL.

<html>
    <head>        
        <title>Test File</title>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
    </head>
    <body>
<?PHP

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors',1);

$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';

$jsonData = file_get_contents($url);

print '<p>',var_dump($jsonData),'</p>';

# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
    echo '<p style="color: #0A0;">fopen is Allowed on this host.</p>';
} else {
    echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}


# Decide what to do based on return value:
if ($jsonData === FALSE) {
    echo "Failed to open the URL ",htmlspecialchars($url);
} elseif ($jsonData === NULL) {
    echo "Function is disabled.";
} else {
   echo $jsonData;
}

?>
    </body>
</html>

如果所有这些都失败了,可能是由于使用了短开标签,<?.因此,本答案中的示例代码已更改为使用<?PHP正常工作,因为无论设置了哪些配置选项,都可以保证在所有版本的PHP中都可以使用.要为您自己的脚本执行此操作,只需替换<?或者<?PHP.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 为什么file_get_contents不起作用?全部内容,希望文章能够帮你解决php – 为什么file_get_contents不起作用?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。