3

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

1
  • 6
    Split the text on newline, loop through all lines until you encounter a string that starts with "Expires: ", cut the first 9 characters and you've got your answer. Commented Nov 22, 2011 at 15:27

2 Answers 2

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

return $result[1];
Sign up to request clarification or add additional context in comments.

1 Comment

Not sure why this was -1'ed, but are the sm modifiers and parentheses necessary?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.