ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 为什么file_get_contents不起作用?

2019-09-19 01:30:03  阅读:274  来源: 互联网

标签:file-get-contents php geocoding


为什么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>

解决方法:

检查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.

标签:file-get-contents,php,geocoding
来源: https://codeday.me/bug/20190919/1812057.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有