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

PHP cURL设置Content-Type: text/xml无效问题求助

问题:PHP cURL设置Content-Type: text/xml无法传递XML数据的解决办法

在AlmaLinux 8的PHP 8.0环境中,使用PHP cURL发送Content-Type: text/xml的POST请求时,接收端无法获取到XML数据,但改用application/x-www-form-urlencoded格式则正常工作。

核心原因

当请求头为text/xml时,PHP不会自动解析POST数据到$_POST数组;而原接收端依赖的$HTTP_RAW_POST_DATA变量在PHP 5.6后已被废弃,PHP 8.0中默认禁用该变量,导致无法获取到原始XML内容。

解决方案

1. 接收端改用php://input获取原始POST数据

这是PHP官方推荐的获取非表单格式POST数据的方式,兼容所有PHP版本(包括PHP 8.0)。

2. 保持发送端的纯XML数据格式

text/xml格式要求请求体为纯XML字符串,无需包装成xml_text=xxx的表单键值对格式(原发送端已正确实现此逻辑)。

修改后的代码示例

接收端post_test_xml.php

<?php
// 使用php://input获取原始POST数据(官方推荐方式)
$xmltext = file_get_contents('php://input');

// 保留原表单格式兼容逻辑(可选)
if (empty($xmltext) && isset($_POST['xml_text'])) {
    $xmltext = $_POST['xml_text'];
}

$xmltext = stripslashes($xmltext);

$myfile = fopen("xml_post.txt", "w") or die("Unable to open file!");
fwrite($myfile, $xmltext);
fclose($myfile);

echo 'Results: '. $xmltext;
?>

发送端代码(无需修改,确认逻辑正确性)

<?php
$dest_url = "http://bgsrv26.internal.bitnetx.com/post_test_xml.php";
$xml = '<test sysVersion="1"/>';

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$dest_url);
curl_setopt($ch,CURLOPT_POST,1); 
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml); // 直接传递纯XML内容
curl_setopt($ch,CURLOPT_ENCODING,'gzip, deflate');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
curl_setopt($ch,CURLOPT_HTTPHEADER,['Content-type: text/xml; charset=utf-8']); 
curl_setopt($ch,CURLOPT_FRESH_CONNECT,TRUE); 
curl_setopt($ch,CURLINFO_HEADER_OUT,true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);

$response = curl_exec($ch);
print "cURL response: " . $response . "\n";

$info = curl_getinfo($ch, CURLINFO_HEADER_OUT);
print "cURL info: ";
var_dump($info);
curl_close ($ch);
?>

验证效果

修改后,发送端发送纯XML+text/xml请求头,接收端通过php://input正确获取原始XML内容,即可正常写入文件并返回结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:26:20