我写了这样的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";
}
其他回答
就像这样:
public function get($curl,$options){
$context = stream_context_create($options);
$file = @file_get_contents($curl, false, $context);
$str1=$str2=$status=null;
sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
if($status==200)
return $file
else
throw new \Exception($http_response_header[0]);
}
我是这样做的……不需要try-catch块…最好的解决方案总是最简单的……享受吧!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
我解决了所有的问题,这是工作的所有环节
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
}
最简单的方法是在file_get_contents前面加上@, 即:
$content = @file_get_contents($site);