使用PHP curl发送xml请求

时间:2013-11-25 05:35:56

标签: php xml web-services curl

我使用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的请求时,此代码是否正确?

    EG。 curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($xmlRequest));

  2. 设置帖子字段时没有设置帖子字段变量。

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

  3. 感谢。

1 个答案:

答案 0 :(得分:13)

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

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


 //setting the curl parameters.
 $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();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);

            // send xml request to a server

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

感谢。