Publish a multidimensional array using CURL and get the result on the server

I am sending data from my local machine to the server using CURL . And the data is a multidimensional array.

 Array ( [0] => stdClass Object ( [id] => 1 ) [1] => stdClass Object ( [id] => 0 ) [2] => stdClass Object ( [id] => 11 ) ) 

I use this code below to send data.

 $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, "my_url"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $array); // $array is my above data 

But on the server, when I try to put this input into a file or just print_r , it gives me this output below

 Array ( [0] => Array [1] => Array [2] => Array ) 

But I want the result to be multidimensional.

I tried with print_r($_POST[0]) , but it gives only Array text.

+7
source share
3 answers

cURL can only accept a simple paired array with a key, where the values ​​are strings, it cannot accept an array like yours, which is an array of objects. However, it accepts the finished POST data string, so you can build the string yourself and pass it:

 $str = http_build_query($array); ... curl_setopt($ch, CURLOPT_POSTFIELDS, $str); 

A print_r($_POST) on the receiving side will be shown:

 Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 0 ) [2] => Array ( [id] => 11 ) ) 
+20
source

I would like to go to serialization and unserialize:

1) Before sending the array, serialize (and set the transfer mode to binary):

 (...) curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); // need this to post serialized data curl_setopt($ch, CURLOPT_POSTFIELDS, serialize($array)); // $array is my above data 

2) When you receive data, perform the following operations:

 $array = unserialize($_POST); 

More here and here

+3
source
 $param['sub_array'] = json_encode($sub_array); 

and on the other hand

 $sub_array= json_decode($_POST['sub_array']); 
+2
source

All Articles