Can PHP cURL retrieve response headers AND body in a single request?

后端 未结 13 1738
粉色の甜心
粉色の甜心 2020-11-22 03:28

Is there any way to get both headers and body for a cURL request using PHP? I found that this option:

curl_setopt($ch, CURLOPT_HEADER, true);
13条回答
  •  渐次进展
    2020-11-22 03:36

    Here is my contribution to the debate ... This returns a single array with the data separated and the headers listed. This works on the basis that CURL will return a headers chunk [ blank line ] data

    curl_setopt($ch, CURLOPT_HEADER, 1); // we need this to get headers back
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    
    // $output contains the output string
    $output = curl_exec($ch);
    
    $lines = explode("\n",$output);
    
    $out = array();
    $headers = true;
    
    foreach ($lines as $l){
        $l = trim($l);
    
        if ($headers && !empty($l)){
            if (strpos($l,'HTTP') !== false){
                $p = explode(' ',$l);
                $out['Headers']['Status'] = trim($p[1]);
            } else {
                $p = explode(':',$l);
                $out['Headers'][$p[0]] = trim($p[1]);
            }
        } elseif (!empty($l)) {
            $out['Data'] = $l;
        }
    
        if (empty($l)){
            $headers = false;
        }
    }
    

提交回复
热议问题