我已经把头发撕了2天试图解决这个问题,我想知道你们有没有人可以提供帮助?我试图将XML字符串发布到服务器,他们声明“所有XML请求应使用HTTP POST方法使用”xml“参数名称发送到我们的服务器”。我已经尝试了很多方法来做到这一点但没有快乐(如果我使用带有表单的javascript它工作正常,但这对项目来说不实用)。请有人指出我正确的方向吗?我将首先在下面发布我无法工作的PHP / CURL代码,然后是可以正常工作的Javascript代码。我想我只是想模仿PHP / CURL代码中的Javascript
PHP / CURL代码
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<Request>
<Head>
<Username>username</Username>
<Password>password</Password>
<RequestType>GetCities</RequestType>
</Head>
<Body>
<CountryCode>MX</CountryCode>
</Body>
</Request>';
$url = "http://example.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
Javacript Code(有效)
function submitForm() {
var reqXML = "<Request><Head><Username>username</Username> <Password>password</Password><RequestType>GetCities</RequestType></Head><Body><CountryCode>MX</CountryCode></Body></Request>";
document.getElementById("xml-request").value = reqXML;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("xml-response").value = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://example.com", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("xml=" + reqXML);
return false;
答案 0 :(得分:0)
由于您希望通过“xml”参数发送XML内容,您可能需要这样做:
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml=" . $xml);
编辑:这是我的工作代码:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?><Request><Head><Username>username</Username> <Password>password</Password><RequestType>GetCities</RequestType></Head><Body><CountryCode>MX</CountryCode></Body></Request>';
$url = "https://postman-echo.com/post"; // URL to make some test
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml=" . $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
echo '<pre>';
echo htmlentities($data);
echo '</pre>';
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
?>