我写了这样的PHP代码
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
但是当我从$site中删除“http://”时,我得到以下警告:
警告: file_get_contents (www.google.com) (函数。file-get-contents]:失败 打开水流:
我试过,试过,但没成功。
我写了这样的PHP代码
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
但是当我从$site中删除“http://”时,我得到以下警告:
警告: file_get_contents (www.google.com) (函数。file-get-contents]:失败 打开水流:
我试过,试过,但没成功。
当前回答
我是这样做的……不需要try-catch块…最好的解决方案总是最简单的……享受吧!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
其他回答
在使用file_get_contents()之前,应该使用file_exists()函数。 这样可以避免php警告。
$file = "path/to/file";
if(file_exists($file)){
$content = file_get_contents($file);
}
你可以在前面加上@: $content = @file_get_contents($site);
这将抑制任何警告-谨慎使用!参见错误控制操作符
编辑:当你删除“http://'”时,你不再寻找一个网页,而是在你的磁盘上一个名为“www.google.....”的文件。
这将尝试获取数据,如果它不起作用,它将捕获错误,并允许您在捕获范围内执行所需的任何操作。
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}
我解决了所有的问题,这是工作的所有环节
public function getTitle($url)
{
try {
if (strpos($url, 'www.youtube.com/watch') !== false) {
$apikey = 'AIzaSyCPeA3MlMPeT1CU18NHfJawWAx18VoowOY';
$videoId = explode('&', explode("=", $url)[1])[0];
$url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $videoId . '&key=' . $apikey . '&part=snippet';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
$value = json_decode(json_encode($data), true);
$title = $value['items'][0]['snippet']['title'];
} else {
set_error_handler(
function () {
return false;
}
);
if (($str = file_get_contents($url)) === false) {
$title = $url;
} else {
preg_match("/\<title\>(.*)\<\/title\>/i", $str, $title);
$title = $title[1];
if (preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $title))
$title = utf8_encode($title);
$title = html_entity_decode($title);
}
restore_error_handler();
}
} catch (Exception $e) {
$title = $url;
}
return $title;
}
function custom_file_get_contents($url) {
return file_get_contents(
$url,
false,
stream_context_create(
array(
'http' => array(
'ignore_errors' => true
)
)
)
);
}
$content=FALSE;
if($content=custom_file_get_contents($url)) {
//play with the result
} else {
//handle the error
}