首页 > 社区问答列表 >PHP cURL:读取特定的响应头信息

  PHP cURL:读取特定的响应头信息

我在PHP中使用cURL进行POST请求,向一个创建资源的终端发送数据。它返回一个带有Location头部的201响应,该头部给出了创建的资源的URL。我还从响应的正文中获取了一些信息。

如何最好地获取响应的纯文本正文,并获取Location头部的值?curl_getinfo函数无法返回该头部的信息,当我尝试这样做时:


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

我只看到一个头部被输出了,就是"HTTP/1.1 201 Created"的响应码。

P粉395056196
P粉395056196

  • P粉713866425
  • P粉713866425   已被采纳   2023-08-07 11:27:20 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('

    Header: %s

    ', $hdr); // Print Content echo $content;

    +0 添加回复