开发者

How to send XML and other post parameters via cURL in PHP

开发者 https://www.devze.com 2022-12-27 17:42 出处:网络
I\'ve used code below to send XML to my REST API. $xml_string_data contains proper XML, and it is passed well to mypi.php:

I've used code below to send XML to my REST API. $xml_string_data contains proper XML, and it is passed well to mypi.php:

    //set POST variables
    $url = 'http://www.server.cu/mypi.php'; 
    $fields = array(
                'data'=>urlencode($xml_string_data)
            );

    //url-ify the data for the POST
    $fields_string = "";
    foreach($fields as $key=>$value) 
    { 
      $fields_string .= $key.'='.$value.'&'; 
    }
    rtrim($fields_string,'&');

    echo $fields_string;

    //open connection
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
        "Expect: "
    ));

    //execute post
    $result = @curl_exec($ch);

But when I've added other field:

    $fields = array(
      'method' => "methodGoPay",
      'data'=>urlencode($xml_string_data)
    );

It stopped to work. On the mypi.php I don't recieve any more POST parameters at all!

Could you you please tell me what to do to send XML and other post parameters in one cURL request?

Please don't suggest using any 开发者_如何学JAVAlibraries, I wan't to acomplish it in plain PHP.


I don't see anything wrong with this script. It's most likely an issue with mypi.php.

You do have an extra & at the end. Maybe that confuses the server? The rtrim doesn't change the $field_string and it returns the trimmed string.

The postfields can be simplified like this,

$fields = array(
      'method' => "methodGoPay",
      'data'=> $xml_string_data // No encode here
);

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号