通过cURL将XML字符串作为参数

时间:2011-04-15 13:10:26

标签: php curl

我试图通过cURL将xml字符串发布到远程perl脚本。我希望将xml字符串作为post参数'myxml'发布。请参阅我在下面使用的代码:

$url = 'http://myurl.com/cgi-bin/admin/xml/xml_append_list_init.pl';
$xml = '<?xml version="1.0" standalone="yes"?>
        <SUB_appendlist>
          <SUB_user>username</SUB_user>
          <SUB_pass>password</SUB_pass>
          <list_id>129</list_id>
          <append>
            <subscriber>
              <address>test@test.comk</address>
              <first_name>Test</first_name>
              <last_name>Test</last_name>
            </subscriber>
          </append>
        </SUB_appendlist>';

$ch = curl_init(); //initiate the curl session 

curl_setopt($ch, CURLOPT_URL, $url); //set to url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // tell curl to return data in a variable 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml", "Content-length: ".strlen($xml))); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, 'myxml='.urlencode($xml)); // post the xml 
curl_setopt($ch, CURLOPT_TIMEOUT, (int)30); // set timeout in seconds 

$xmlResponse = curl_exec($ch); 
curl_close ($ch); 

但是远程服务器没有看到'myxml'参数中的数据。我在$ xmlResponse

中得到以下回复
HTTP/1.1 200 OK
Date: Fri, 15 Apr 2011 12:00:44 GMT
Server: Apache/2.2.9 (Debian)
Vary: Accept-Encoding
Content-Length: 0
Content-Type: text/html; charset=ISO-8859-1

我不是一个cURL专家,所以我可能在mu cURL请求中做了一些显然是错误的事情。如果有人可以解决任何问题或发现任何问题,我将不胜感激。希望这是足够的信息。

干杯, 阿德里安。

2 个答案:

答案 0 :(得分:1)

邮件正文不是text / xml数据。它是application / x-www-form-urlencoded数据。您有包含XML的表单数据,而不是纯XML。

您的问题类似于尝试在MS Word中打开MyDoc.zip。在将其作为Word处理之前,您必须将其作为zip文件处理。

根据我对PHP手册的阅读,您希望删除

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml", "Content-length: ".strlen($xml))); 

并将POSTFIELDS行更改为:

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'myxml' => $xml
));

答案 1 :(得分:-1)

这不是所有浏览器的正确内容类型。

请参阅this article

有时xml的内容类型为:application/rss+xml