【问题标题】:Send xml request using PHP curl使用 PHP curl 发送 xml 请求
【发布时间】:2013-12-09 17:31:45
【问题描述】:

我使用 PHP curl 向 web 服务发送 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);

谢谢。

【问题讨论】:

  • 我已经解决了我的问题。请看我下面的帖子。

标签: php xml web-services curl


【解决方案1】:

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

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

谢谢。

【讨论】:

  • $xmlRequest 你还没有解释这个变量@cha
  • xml 格式的字符串?没有编码或转义?
  • 我正在使用 post 方法发送数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多