首页  >  问答  >  正文

PHP CURLOPT_WRITEFUNCTION将头部信息返回到正文中

当我包含 curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write_flush') 时,我将标头插入到 $body 中。但如果没有 CURLOPT_WRITEFUNCTION 一切正常。我该怎么做才能阻止标头插入 $body

<?php

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    function curl_write_flush($curl_handle, $chunk) { 
        echo $chunk;
        ob_flush();
        flush();
        return strlen($chunk);
    }
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curl_write_flush'); // WORKS WITHOUT

    $response = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

    curl_close($ch);

    $headers = substr($response, 0, $header_size);
    $body = substr($response, $header_size);

    die($body);

?>

P粉799885311P粉799885311237 天前482

全部回复(1)我来回复

  • P粉262113569

    P粉2621135692024-03-20 18:13:33

    https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html

    要么去掉 curl_setopt($ch, CURLOPT_HEADER, 1);,否则您必须自己从回调数据中解析出标头。

    您还可以使用CURLOPT_HEADERFUNCTION,如本答案所示:

    https://stackoverflow.com/a/41135574/1064767

    回复
    0
  • 取消回复