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

如何将XHR POST请求转换为PHP file_get_contents实现并传递请求数据

要实现xhr.send()发送请求体的效果,你只需要在$opts的http配置数组中新增content字段,将待发送的JSON数据赋值给该字段即可,content字段的作用就对应XHR中send()方法传入的请求体内容。

修改后的完整代码如下:

$url = "https://example.com/test";

// 建议用json_encode生成JSON,避免手动拼写语法错误
$postData = [
    'thing1' => 'abc',
    'thing2' => 'def',
    'thing3' => 'ghi'
];
$content = json_encode($postData);

$opts = [
    "http" => [
        "method" => "POST",
        "header" => 
            "Content-Type: application/json; charset=UTF-8\r\n".
            "Referer: https://example.com\r\n".
            "X-Requested-With: XMLHttpRequest\r\n",
        // 新增此行配置即可完成请求体发送
        "content" => $content
    ]
];

// 第二个参数$use_include_path请求远程地址时设为false即可,无需检索本地路径
echo file_get_contents($url, false, stream_context_create($opts));

补充注意点:

  • 头信息拼接时建议用标准HTTP换行符\r\n,替代单纯的\n,避免部分对请求格式校验严格的服务端识别异常。
  • 若需要手动写JSON字符串,需确保JSON格式合法,key和字符串值用双引号包裹,避免服务端解析失败。

内容的提问来源于stack exchange,提问作者Pengalor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:48:02