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

I used the following code to send XML to the REST API. $ xml_string_data contains the correct 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 added another field:

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

He stopped working. On mypi.php, I don't get any POST parameters at all!

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

Please do not offer to use any libraries, I will not understand simple PHP.

+4
source share
1 answer

I do not see anything wrong with this script. This is most likely a problem with mypi.php.

You have an extra and at the end. Maybe this confuses the server? Rtrim does not change $ field_string and returns a trimmed string.

Postfields can be simplified as follows:

 $fields = array( 'method' => "methodGoPay", 'data'=> $xml_string_data // No encode here ); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields)); 
+3
source

Source: https://habr.com/ru/post/1307766/


All Articles