You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP Curl获取WordPress API的X-WP-Total等响应头?

解决PHP Curl无法获取WordPress API的X-WP-*响应头问题

我尝试通过PHP Curl请求WordPress文章API(示例接口:https://news.harvard.edu/wp-json/wp/v2/posts),读取X-WP-Total和X-WP-TotalPages这类分页相关响应头,但输出的结果里始终没有这些字段。我的代码如下:

$url = "https://news.harvard.edu/wp-json/wp/v2/posts";
$headers = [];
$data=[];
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($curl, CURLOPT_TIMEOUT, 0);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
    function ($curl, $header) use (&$headers) {
        $len = strlen($header);
        $header = explode(':', $header, 2);
        if (count($header) < 2) // ignore invalid headers
            return $len;

        $headers[strtolower(trim($header[0]))][] = trim($header[1]);

        return $len;
    }
);
$response = curl_exec($curl);

if ($response == false) {
    if(curl_errno($curl)>=1){
        $error = curl_errno($curl);
        curl_close($curl);
        $data = ["curl_error"=>$error];
    }
}else{
    
    $data = [
        "headers"=>$headers
    ];

    curl_close($curl);
}

var_dump($data);     

// $data doesn't contain X-WP-Total and X-WP-TotalPages

问题原因

  1. Curl选项冲突:同时启用CURLOPT_HEADER = true和CURLOPT_HEADERFUNCTION回调会导致异常。当设置CURLOPT_HEADERFUNCTION时,Curl会通过回调处理响应头,但CURLOPT_HEADER = true会让响应头直接混入$response结果中,回调无法正常收集所有头信息。
  2. 缺少Curl初始化:代码中没有调用curl_init()创建Curl资源,这会导致所有curl_setopt调用无效,直接引发请求失败。

修复后的代码

$url = "https://news.harvard.edu/wp-json/wp/v2/posts";
$headers = [];
$data = [];

// 初始化Curl资源
$curl = curl_init();

// 设置合理超时(避免无限等待)
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); 
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// 关闭CURLOPT_HEADER,让回调单独处理响应头
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
    function ($curl, $header) use (&$headers) {
        $len = strlen($header);
        // 跳过空行(响应头结束标志)
        if (trim($header) === '') {
            return $len;
        }
        $header = explode(':', $header, 2);
        if (count($header) < 2) {
            return $len;
        }
        $key = strtolower(trim($header[0]));
        $value = trim($header[1]);
        // 兼容重复头字段,合并为数组
        if (isset($headers[$key])) {
            if (!is_array($headers[$key])) {
                $headers[$key] = [$headers[$key]];
            }
            $headers[$key][] = $value;
        } else {
            $headers[$key] = $value;
        }
        return $len;
    }
);

$response = curl_exec($curl);

if ($response === false) {
    $error = curl_errno($curl);
    $data = ["curl_error" => $error];
} else {
    // 提取需要的分页头
    $totalPosts = $headers['x-wp-total'] ?? 0;
    $totalPages = $headers['x-wp-totalpages'] ?? 0;
    $data = [
        "headers" => $headers,
        "x-wp-total" => $totalPosts,
        "x-wp-totalpages" => $totalPages,
        "response_body" => json_decode($response, true)
    ];
}

curl_close($curl);
var_dump($data);

关键修复点

  • 添加curl_init()初始化Curl资源,确保后续配置生效
  • 将CURLOPT_HEADER设为false,避免和CURLOPT_HEADERFUNCTION冲突
  • 优化回调函数,处理空行和重复头字段
  • 设置合理的超时时间,避免无限等待请求

内容的提问来源于stack exchange,提问作者Ian Mukunya Douglas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:18:19