PHP curl是否可以在单个请求中返回带有正文和标头的对象?

问题描述:

curl是否可以返回将标头和正文作为单独属性的对象?

Can curl return an object that has the headers and body as separate properties?

这是我现在正在做的事情。这将返回一个String(?),它的标题是头,然后是正文:

Here is what I'm doing now. This returns a String(?) with the header first and then body after:

$session = curl_init($url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_HEADER, true);
$response = curl_exec($session);
echo $response; // string

我想要的是:

...
$response = curl_exec($session);
$header = $response->headers;
$body = $response->body;

我看到了一个类似的问题,建议同时请求标头和正文,然后解析结果。我不是在问这个。

I've seen a similar question that suggests requesting both the headers and body and then parsing the results. I'm not asking about that.

我特别想问一下返回对象的正文和标头作为单独的属性。

I'm specifically asking about returning an object with the body and headers as separate properties.

如果答案为否,那是不可能的,那么我会接受该答案。我还将接受没有 curl 不会这样做,但这是另一个称为 swurl (或其他)的东西,确实返回了一个对象...

If the answer is "No, that's not possible" then I'll accept that answer. I'll also accept "No curl doesn't do that but here is another called swurl (or whatever) that does return an object..."

标题和正文由空行分隔,您可以在该行上拆分:

Headers and body are separated by a blank line, you can can just split on that:

[$headers, $body] = explode("\r\n\r\n", $response, 2);

面向对象的企业版:

$response = new stdClass();
[$response->headers, $response->body] = explode("\r\n\r\n", curl_exec($session),  2);