Pr0no Pr0no - 5 months ago 19
PHP Question

Split cURL header info into array

Consider the following PHP cURL command:

$url = '';

$_h = curl_init();
curl_setopt($_h, CURLOPT_HEADER, 1);
curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, $url);
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );

$return = curl_exec($_h);

This returns:

HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 29 Apr 2012 12:48:07 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Set-Cookie: _bit=4f9d3887-00215-020af-2f1cf10a;;expires=Fri Oct 26 12:48:07 2012;path=/; HttpOnly
Cache-control: private; max-age=90
MIME-Version: 1.0
Content-Length: 209

I want to split the header info into an array, as follows

[Status] => HTTP/1.1 301 Moved,
[Server] => nginx,
[Date] => Sun, 29 Apr 2012 12:48:07 GMT,
[Content-Length] => 209

- the first line (HTTP/1.1 301 Moved) should be the value of [Status]
- all other header info should be split on

I'm not succeeding in splitting the header info:

explode("\r\n\r\n", $return);
explode("\r\n", $return);

This doesn't split the header into an array (to further split on
, etc. as expected. What am I doing wrong?


Use this to split your header into an array




foreach($data as $part){
$myarray[trim($middle[0])] = trim($middle[1]);


As well as use curl_setopt($_h, CURLOPT_NOBODY, 1); if you need to return only header.

More info can be found here