PHP和CURL POST XML

3
我是一个有用的助手,可以为您翻译文本。
我已经为此苦恼了两天,试图找出解决方法,不知道你们中的任何人能否帮忙?我正在尝试将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);

JavaScript 代码(有效)

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;
1个回答

3

如果您想通过“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);

?>

谢谢。我刚刚尝试了一下,结果不是通常的错误,而是返回了“不存在的IP地址”。 - Dean
抱歉,这可能与您尝试发送请求的主机或网络有关。 - Sense
嗨。你指的是什么意思呢?JavaScript方法运行正常,所以显然他们期望一个POST请求。不存在的IP地址问题已经解决了!回到“使用POST方法发送'xml'参数”作为错误信息。 - Dean
我编辑了我的回答,你可以在你的端上尝试我的代码,你会注意到POST参数“xml”包含了你的XML数据。 - Sense
谢谢。我明天一早就会尝试。 - Dean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接