您应该使用cURL 这样做,不仅因为它是way faster 而不是file_get_contents,还因为它具有更多功能。使用它的另一个原因是,正如 Xeoncross 在 cmets 中正确提到的那样,出于安全原因,您的虚拟主机可能会禁用 file_get_contents。
一个基本的例子是这个:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
如果需要请求返回的数据,需要指定CURLOPT_RETURNTRANSFER选项:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true ); // Fetch the contents too
$html = curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
有很多 cURL 选项,例如,您可以设置请求超时:
curl_setopt( $curl_handle, CURLOPT_CONNECTTIMEOUT, 2 ); // 2 second timeout
有关所有选项的参考,请参阅curl_setopt() 参考。