Parsing PHP CURL data
I have been messing with CURL for the past day and I cannot seem to figure out how to parse out the return data. I know I could write a REGEX to extract data from the response but it seems like there is some function I am probably missing. Here is what I would like to try and do.
I want to make POST to a different domain and get back 3 things 1. the response headers 2. the response开发者_运维知识库 data 3. a session cookie
Is there a way I can get those 3 things back separately? right now I just get back a plain text response with the response header and the response data. I would like to be able to do something like
$Response = curl_exec($Curl_Connection);
$ResponseData = $Response['Data'];
$ResponseHeader = $Response['Header'];
ResponseCookie = $Response['Cookie'];
Does curl provide anything like this?
As I answered:
no post data returned when requesting headers CURLOPT_HEADER. PHP CURL
Add:
curl_setopt($Curl_Connection, CURLOPT_HEADER, TRUE);
$Response = curl_exec($Curl_Connection);
$curlHeaderSize=curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$ResponseData = mb_substr($result, $curlHeaderSize);
$ResponseHeader = mb_substr($result, 0, $curlHeaderSize);
preg_match_all('|Set-Cookie: (.*);|U', $ResponseHeader, $content);
$ResponseCookie = implode(';', $content[1]);
According to the curl docs:
/* TRUE to include the header in the output. */
curl_setopt($Curl_Connection, CURLOPT_HEADER, TRUE);
So the header is added to the output of curl_exec command. I've been spitting this out and I don't see any way to retrieve the header separately from the response body. It gets worse when you start reading compressed output (zipped, inflated)
On top of that, it's a one big string, not an array, so in case you you want the header in a format like for example curl_getinfo brings back an array.
The easiest is to do this:
$backend_output = curl_exec($ch);
list( $backend_response_headers, $backend_response_body)
= explode("\r\n\r\n", $backend_output, 2);
That will split those 2 up, but you end up with a string for the response header, not an array which would be so much more helpful. Now making an arrray from that isn't so evident, even with a regex as you can't split on for example something simple like /(\w)\s:(\w)/ as ':' can occur in certain fields. It would be very cool if curl would offer the headers seperately but so far as I go through the docs, it doesn't seem to be there.
Concerning your session cookies, I believe you need to use CURLOPT_COOKIESESSION = true option for that, but I have less experience on cookies as I hardly ever have the professional need to use them. Good luck
update: The headers you can parse with http://php.net/manual/en/function.http-parse-headers.php or a custom function from the user comment section if you lack pecl.
精彩评论