How to remove HTTP headers from CURL response?
You can write a simple PHP curl program to download a page. Every HTTP response contains a Header and the contents. In most cases, you will be concerned more about the contents. By default, curl response will give you the contents. But you can also specify that you need only the contents and not the header using the option CURLOPT_HEADER in your program with the curl_setopt function
curl_setopt($curlHandle, CURLOPT_HEADER, false);
Let’s see the complete program which is also give here.
<?php
function downloadURL($URL) {
if(!function_exists('curl_init')) {
die ("Curl PHP package not installed\n");
}
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
/*Don't return the headers*/
curl_setopt($curlHandle, CURLOPT_HEADER, false);
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
return $response;
}
echo downloadURL("http://www.mozilla.org/");
?>
Let’s execute the program
$ php download.php | less
The output of the program will be something like this
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="DC.description" content="" />
<meta name="DC.subject" content="" />
<meta name="DC.creator" content="Happy Cog Studios - http://www.happycog.com" />
If you want to see the difference by enabling CURLOPT_HEADER to true.
Comments:
This is great as i can now use json_decode directly on my curl response which i couldn’t do with headers set to TRUE.
however, i would like headers set to TRUE so that i can test that i got a valid response… so if i do this… how do i get at the contents.. i am having no luck pulling out my JSON result using a preg_match. Any thoughts.
brute force approach would be to do curl twice; once to get and test header and then 2nd to curl with headers set to false to get contents… but this seems inefficient.