在PHP中使用cURL上传XML文件,核心是通过curl_setopt函数设置CURLOPT_POSTFIELDS。这个值可以直接是XML字符串,也可以是读取本地文件后的内容。关键是要把请求头中的Content-Type设为text/xml或application/xml,让服务端正确解析。

直接发送XML字符串
当XML内容已经在变量中时,把字符串赋给CURLOPT_POSTFIELDS即可。下面示例向接口提交一段订单XML。
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<order>
<id>1001</id>
<name>测试订单</name>
</order>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.ipipp.com/upload');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml; charset=UTF-8',
'Content-Length: ' . strlen($xml)
));
$response = curl_exec($ch);
if ($response === false) {
echo '错误: ' . curl_error($ch);
} else {
echo '响应: ' . $response;
}
curl_close($ch);
?>
上传本地XML文件
如果XML文件在服务器本地,先用file_get_contents读取,再传给CURLOPT_POSTFIELDS。
<?php
$filePath = '/data/order.xml';
if (!file_exists($filePath)) {
die('文件不存在');
}
$xmlContent = file_get_contents($filePath);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.ipipp.com/upload');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlContent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/xml'
));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
使用数组表单上传文件
若接口要求以multipart/form-data接收文件字段,可用curl_file_create包装文件,此时CURLOPT_POSTFIELDS传数组。
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.ipipp.com/upload_file');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
// 注意这里传数组,cURL会自动用multipart格式
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'xml' => curl_file_create('/data/order.xml', 'application/xml', 'order.xml')
));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
常见注意点
- 直接发XML字符串时不要误用数组,否则会被编码成表单格式。
- 用
curl_setopt设置CURLOPT_POST为true,否则POSTFIELDS不生效。 - 本地文件读取失败要提前判断,避免发送空内容。
总结:CURLOPT_POSTFIELDS既能接收字符串也能接收数组,上传XML选字符串直发或文件对象表单均可,按接口要求选方式并设置对应Content-Type即可。
PHPcURLXML_upload修改时间:2026-07-26 18:48:11