Check file_get_contents
PHP Manual return value. If the value is FALSE
then it could not read the file. If the value is NULL
then the function itself is disabled.
To learn more what might gone wrong with the file_get_contents
operation you must enable error reporting and the display of errors to actually read them.
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents
function is allow_url_fopen
. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.
<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>
If all of this fails, it might be due to the use of short open tags, <?
. The example code in this answer has been therefore changed to make use of <?php
to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <?
or <?php
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…