如何使用XML格式的数据发出POST请求并获得结果

时间:2014-04-18 07:58:35

标签: php xml curl

我有一个API,它说所有请求都是以XML格式的数据作为POST请求发出的,它给了我一个示例XML数据:

<?xml version="1.0" ?>
<Request>
    <SystemName>SomeSystemName</SystemName>
    <Client>SomeClientID</Client>
    <Method action="SomeAction">MethodParams</Method>
</Request>

现在我使用curl来完成它,就像在这个函数中一样:

function curl_post_xml($url, $xml, array $options = array()) 
{ 
    $defaults = array( 
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $xml,
        CURLOPT_HEADER => 0, 
        CURLOPT_URL => $url, 
        CURLOPT_FRESH_CONNECT => 1, 
        CURLOPT_RETURNTRANSFER => 1, 
        CURLOPT_FORBID_REUSE => 1, 
        CURLOPT_TIMEOUT => 4,
    ); 

    $ch = curl_init(); 
    curl_setopt_array($ch, ($options + $defaults)); 
    if( ! $result = curl_exec($ch)) 
    { 
        trigger_error(curl_error($ch)); 
    } 
    curl_close($ch); 
    return $result; 
} 

$xml中我从上面放了那个XML字符串。我做得对吗?因为我听说在使用POST时,数据必须是键值格式,但API没有说明我应该为哪个变量分配XML字符串。

2 个答案:

答案 0 :(得分:1)

Am I doing it right? Because I heard that when using POST, the data must be in key-value format,

是的,你是对的,你必须指明你发送的所有内容都是XML

CURLOPT_HTTPHEADER => array("Content-Type: application/xml"),
// or text/xml instead of application/xml

您无需将$xml置于密钥下。只要你正在做的就好了,很好。

答案 1 :(得分:1)

这对我有用:

<?php 
    $xml_data ='<Request>
    <SystemName>SomeSystemName</SystemName>
    <Client>SomeClientID</Client>
    <Method action="SomeAction">MethodParams</Method>
</Request>';


$URL = "https://www.yourwebserver.com/path/";

            $ch = curl_init($URL);
            curl_setopt($ch, CURLOPT_MUTE, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);


?>