我写了这样的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]:失败 打开水流:
我试过,试过,但没成功。
当前回答
我解决了所有的问题,这是工作的所有环节
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;
}
其他回答
一种替代方法是抑制错误并抛出稍后可以捕获的异常。如果在代码中有多个对file_get_contents()的调用,这尤其有用,因为您不需要手动抑制和处理所有这些调用。相反,可以在一个try/catch块中对该函数进行多次调用。
// Returns the contents of a file
function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}
// Example
try {
file_contents("a");
file_contents("b");
file_contents("c");
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}
我最喜欢的方法很简单:
if (($data = @file_get_contents("http://www.google.com")) === false) {
$error = error_get_last();
echo "HTTP request failed. Error was: " . $error['message'];
} else {
echo "Everything went better than expected";
}
我在尝试上面@enobrev的try/catch后发现了这一点,但这允许更短的长度(在我看来,更可读)代码。我们简单地使用error_get_last来获取最后一个错误的文本,失败时file_get_contents返回false,因此简单的“if”就可以捕获它。
您可以使用这个脚本
$url = @file_get_contents("http://www.itreb.info");
if ($url) {
// if url is true execute this
echo $url;
} else {
// if not exceute this
echo "connection error";
}
这将尝试获取数据,如果它不起作用,它将捕获错误,并允许您在捕获范围内执行所需的任何操作。
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}
我是这样做的……不需要try-catch块…最好的解决方案总是最简单的……享受吧!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}