使用 PHP cURL 下载 URL 的内容

在特定 URL 下载内容是 Internet 上的常见做法,尤其是由于 Amazon、Alexa、Digg 等提供的 Web 服务和 API 的使用增加。PHP 的 cURL 库通常带有默认的共享主机配置,允许Web 开发人员完成此任务。

代码

/* gets the data from a URL */
function get_data($url) {
	$ch = curl_init();
	$timeout = 5;
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

用法

$returned_content = get_data('https://davidwalsh.name');

或者,您可以远程使用 file_get_contents 函数,但许多主机不允许这样做。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏