Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl request with headers - separate body a from a header [duplicate]

Tags:

php

Ive got a code

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);        
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $ret = curl_exec($ch);
    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

Now i want to extract the body from $ret without headers. Any idea how to do it?

like image 244
Michal Avatar asked Apr 30 '12 13:04

Michal


2 Answers

raina77ow's response is good. From the comments it looks like there are a few conditions that would cause the "explode" to not work. I found a way that works better for me and thought I'd share.

By calling curl_getinfo($ch, CURLINFO_HEADER_SIZE) you can get the length of the response header. So I did the following:

// Original Code
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);        
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$ret = curl_exec($ch);
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Added Code
$header_len = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($ret, 0, $header_len);
$body = substr($ret, $header_len);

// Back to Original Code
curl_close($ch);

This is working great for me. I hope it helps someone else.

like image 192
natiupiru Avatar answered Oct 15 '22 02:10

natiupiru


How about this:

list($headers, $content) = explode("\r\n\r\n", $ret, 2);

... which should give you the body of your request in the $content variable?

like image 26
raina77ow Avatar answered Oct 15 '22 04:10

raina77ow