PHP cURL: Read a specific response header

那年仲夏 提交于 2019-12-07 20:22:37

问题


I am using cURL in PHP to POST to an endpoint that is creating a resource. It returns a 201 response with a Location header giving the URL of the resource created. I also get some information in the body of the response.

What's the best way to get the plain-text body of the response, and also get the value of the location header? curl_getinfo doesn't return that header, and when I do this:

    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) {
        var_dump($header);
    });

I only see one header dumped out--the "HTTP/1.1 201 Created" response code.


回答1:


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER,true);

$result = curl_exec($ch);

curl_close($ch);

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

// Print header
foreach (explode("\r\n",$headers) as $hdr)
    printf('<p>Header: %s</p>', $hdr);

// Print Content
echo $content;


来源:https://stackoverflow.com/questions/21291675/php-curl-read-a-specific-response-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!