如何合并两段PHP cURL代码,单次请求获取内容与Content-Type
合并cURL请求,单次请求同时获取页面内容与Content-Type
你当前通过两个独立的cURL函数对同一页面发起两次请求,分别获取Content-Type和页面内容。可以通过整合请求逻辑,仅发起一次请求就能同时拿到这两个数据,避免重复请求浪费资源。
原代码(两次请求)
获取Content-Type的函数:
function get_content_type_curl($url_content_type) { $agent_content_type = $_SERVER['HTTP_USER_AGENT']; $ch_content_type = curl_init(); curl_setopt($ch_content_type, CURLOPT_URL, $url_content_type); curl_setopt($ch_content_type, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch_content_type, CURLOPT_HEADER, 0); curl_setopt($ch_content_type, CURLOPT_NOBODY, 1); curl_setopt($ch_content_type, CURLOPT_USERAGENT, $agent_content_type); curl_setopt($ch_content_type, CURLOPT_FOLLOWLOCATION, 1); curl_exec($ch_content_type); $content_type = curl_getinfo($ch_content_type, CURLINFO_CONTENT_TYPE); curl_close($ch_content_type); return $content_type; } $content_type = get_content_type_curl("https://example.com"); header('Content-Type:' . $content_type);
获取页面内容的函数:
function file_get_contents_curl($url) { $agent = $_SERVER['HTTP_USER_AGENT']; $ch = curl_init(); curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_VERBOSE, true); $data = curl_exec($ch); curl_close($ch); return $data; } $homepage = file_get_contents_curl("https://example.com"); echo $homepage;
解决方案(单次请求)
整合两个函数的逻辑,发起一次完整请求(不要设置CURLOPT_NOBODY,否则只会获取响应头),同时拿到页面内容和Content-Type:
function fetch_content_and_type($url) { $agent = $_SERVER['HTTP_USER_AGENT']; $ch = curl_init(); // 整合公共配置项 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_VERBOSE, true); // 执行请求,获取页面内容 $content = curl_exec($ch); // 通过curl_getinfo获取Content-Type $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); // 返回包含内容和类型的数组 return [ 'content' => $content, 'content_type' => $content_type ]; } // 调用示例 $result = fetch_content_and_type("https://example.com"); // 设置响应头 header('Content-Type:' . $result['content_type']); // 输出页面内容 echo $result['content'];
关键说明
- 移除了
CURLOPT_NOBODY选项:该选项会让cURL只发送HEAD请求,无法获取响应体内容,必须去掉才能拿到页面字符串。 - 整合了两个函数中的公共cURL配置,避免重复设置。
- 通过
curl_exec()获取页面内容,同时用curl_getinfo($ch, CURLINFO_CONTENT_TYPE)从请求信息中提取Content-Type,无需额外请求。
内容的提问来源于stack exchange,提问作者Mehul Kumar
相关产品推荐
相关产品推荐

