I try to send a multi array via cURL
but I can't find a nice way to do it.
My code example:
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
This will work and give the result I want on the curl_init()
site:
print_r( $_POST )
:
Array (
[a] => testa
[b] => testb
[c] => Array (
[d] => test1
[e] => test2
)
)
I'd like to add the c array dynamically like:
$c['d'] = 'test1';
$c['e'] = 'test2';
But if I try to add an array with array_push
or []
I always get and (string)Array in the Array without data.
Can anyone help me to do it?
The whole code for faster testing:
$url = 'url_to_test.php';
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' );
$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFE开发者_运维百科R, 1 );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$buffer = curl_exec ($ch);
curl_close ($ch);
echo $buffer;
The test.php
print_r($_POST);
Thanks for any help!
cheers
In
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' )
You've simply added new string keys "c[d]" and "c[e]".
If you want a nested array, use:
$data = array( 'a' => 'testa', 'b' => 'testb', 'c' =>
array( 'd' => 'test1', 'e' => 'test2' )
)
-- EDIT --
You're trying to set POST data, which is essentially a set of key value pairs. You can't provide a nested array. You could, however, serialize the nested array and decode it at the other end. Eg:
$post_data = array('data' => serialize($data));
And at the receiving end:
$data = unserialize($_POST['data']);
here is your solution
$urltopost = "http://example.com/webservice/service.php";
$datatopost = array (0 =>array('a'=>'b','c'=>'d'),1 =>array('a'=>'b','c'=>'d'),2 =>array('a'=>'b','c'=>'d'),3 =>array('a'=>'b','c'=>'d'));
$post_data = array('data' => serialize($datatopost));
$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
echo "<pre>";
print_r(unserialize($returndata));
service.php code
$temp = unserialize($_POST['data']);
echo serialize($temp);
精彩评论