使用PHP curl发送xml请求

6
我使用PHP curl发送XML请求到webservice并获取响应。我的代码如下。
$url = "https://path_to_service.asp";
try{
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POSTFIELDS,  urlencode($xmlRequest));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_VERBOSE, 0);
            $data = curl_exec($ch);

            //convert the XML result into array
            if($data === false){
                $error = curl_error($ch);
                echo $error; 
                die('error occured');
            }else{

                $data = json_decode(json_encode(simplexml_load_string($data)), true);  
            }
            curl_close($ch);

        }catch(Exception  $e){
            echo 'Message: ' .$e->getMessage();die("Error");
    }

我只从第三方网络服务中得到了这个错误。他们说请求方式可能无效,但XML代码是正确的。

"XML load failed. [Invalid at the top level of the document.]"

但是我的问题是:

  1. 当使用XML请求时,这段代码是否正确?

    例如:curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($xmlRequest));

  2. 设置POST字段时没有POST字段变量需要设置。

    例如:curl_setopt($ch, CURLOPT_POSTFIELDS, "xmlRequest=" . $xmlRequest);

谢谢。


我已经解决了我的问题。请查看我之前的帖子。 - cha
1个回答

14

我分享了我的解决方案,希望对他人有所帮助。

$url = "https://path_to_service.asp";

//setting the curl headers
$headers = array(
    "Content-type: text/xml;charset=\"utf-8\"",
    "Accept: text/xml",
    "Cache-Control: no-cache",
    "Pragma: no-cache",
    "SOAPAction: \"run\""
);

try{

    $ch = curl_init();

    //setting the curl options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $xmlRequest);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $data = curl_exec($ch);

    //convert the XML result into array
    if($data === false){
        $error = curl_error($ch);
        echo $error;
        die('error occured');
    }else{
        $data = json_decode(json_encode(simplexml_load_string($data)), true);
    }

    curl_close($ch);

}catch(Exception  $e){
    echo 'Message: '.$e->getMessage();
    die("Error");
}

谢谢。


1
$xmlRequest 这个变量你还没有解释。 - saikiran
XML格式的字符串?没有编码或转义? - ahnbizcad
我正在使用POST方法发送数据。 - cha

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