Max Rose-Collins
Max Rose-Collins

Reputation: 1924

use cURL to get HTTP header and save to variable

I am using this to grab a XML feed and the HTTP headers

// Initiate the curl session
$ch = curl_init();

// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);

// Allow the headers
curl_setopt($ch, CURLOPT_HEADER, true);

// Return the output instead of displaying it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the curl session
$output = curl_exec($ch);

// Close the curl session
curl_close($ch);

// Cache feed
file_put_contents($filename, $output);

// XML to object
$output = simplexml_load_string($output);

// Return the output as an array
return $output;

And it returns these headers

HTTP/1.1 200 OK
Cache-Control: public, max-age=30
Content-Length: 5678
Content-Type: text/xml
Expires: Tue, 22 Nov 2011 15:12:16 GMT
Last-Modified: Tue, 22 Nov 2011 15:11:46 GMT
Vary: *
Server: Microsoft-IIS/7.0
Set-Cookie: ASP.NET_SessionId=1pfijrmsqndn5ws3124csmhe; path=/; HttpOnly
Data-Last-Updated: 11/22/2011 15:11:45
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 22 Nov 2011 15:11:46 GMT

I only want it to return one part of the HTTP header, which is

Expires: Tue, 22 Nov 2011 15:12:16 GMT

and save that to a variable, how do I do this? I have been looking through the PHP manual but can't work it out

Upvotes: 3

Views: 5839

Answers (2)

hattila
hattila

Reputation: 500

You can use PHP's get_headers($url, 1) function, which returns all the header information in an array, and if you set the second optional param to 1 (non-zero), then it parses it into an associative array like:

array(
    [...] => ...,
    [Expires] => 'what you need',
    [...] => ...
) 

http://php.net/manual/en/function.get-headers.php

Upvotes: 2

Jauzsika
Jauzsika

Reputation: 3251

preg_match('~^(Expires:.+?)$~ism', $headers, $result);

return $result[1];

Upvotes: 3

Related Questions