发送XML数据到指定URL
作者:杨锦龙时间:2025-10-16点击量:0次
/**
* 发送XML数据到指定URL
* @param string $xml
* @param string $url
* @return string
*/
private function postXmlCurl($xml, $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 设置HTTP头
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml)
));
// 如果是HTTPS,可能需要证书(企业级应用)
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
// curl_setopt($ch, CURLOPT_SSLCERT, '/path/to/apiclient_cert.pem');
// curl_setopt($ch, CURLOPT_SSLKEY, '/path/to/apiclient_key.pem');
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
/**
* 将数组转换为XML
* @param array $data
* @return string
*/
private function arrayToXml($data) {
$xml = '<xml>';
foreach ($data as $key => $value) {
// 对特殊字符进行XML转义
$xml .= '<' . $key . '>' . $this->xmlSpecialChar($value) . '</' . $key . '>';
}
$xml .= '</xml>';
return $xml;
}
/**
* 转换特殊字符,防止XML解析错误
* @param string $str
* @return string
*/
private function xmlSpecialChar($str) {
// 转义 &, <, >, ", ' 这些特殊字符
$str = htmlspecialchars($str, ENT_XML1, 'UTF-8');
return $str;
}
/**
* 将XML转换为数组
* @param string $xml
* @return array
*/
private function xmlToArray($xml) {
// 禁用外部实体加载,防止XXE攻击
libxml_disable_entity_loader(true);
$result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $result;
}