使用PHP curl发送xml请求


Send xml request using PHP curl

我已经使用PHP curl向webservice发送XML请求并获得响应。我的代码如下。

$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. 设置过帐字段时没有要设置的过帐字段变量。

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

谢谢。

我正在与其他人分享我的解决方案,这将对其他人有所帮助。

$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");
}

谢谢。