为什么file_get_contents不起作用?

PVJ*_*AZZ 11 php geocoding 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&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>
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 31

检查file_get_contents PHP手动返回值.如果该值是,FALSE那么它无法读取该文件.如果该值是,NULL那么函数本身被禁用.

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

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
Run Code Online (Sandbox Code Playgroud)

您可以通过检查服务器上的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>
Run Code Online (Sandbox Code Playgroud)

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

  • @Shamim但是当禁用短打开标签时,整个脚本都很重要 (2认同)
  • @Shamim Hafiz:它确实很重要,因为这可以区分执行与否.如果服务器已禁用[`short_open_tag`](http://php.net/manual/en/ini.core.php),则不会执行此操作. (2认同)

Nic*_*k F 6

如果PHP的allow_url_fopenini指令设置为true,并且如果curl也不起作用(请参阅此答案以获取如何使用它的示例而不是file_get_contents),那么问题可能是您的服务器有防火墙阻止脚本获取内容任意网址(可能允许恶意代码获取内容).

我遇到了这个问题,并发现我的解决方案是编辑防火墙设置以明确允许对相关域(或IP地址)的请求.