Posting multidimensional array with PHP and CURL
You'd have to build the POST string manually, rather than passing the entire array in. You can then override curl's auto-chose content header with:
curl_setopt($c, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
Serializing/json-ifying would be easier, but as you say, you have no control over the receiving end, so you've got a bit of extra work to do.
Sending a multidimensional array using cURL and foreach in php
Thanks to This awesome reply I understood I must use $POST
only.
sender:
<?php
function post_to_url($url, $data) {
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($post, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($post);
curl_close($post);
}
if (isset($_POST['submit'])){
$name = addslashes(strip_tags($_POST["name"]));
$address = addslashes(strip_tags($_POST["address"]));
$email = addslashes(strip_tags($_POST["email"]));
$job = addslashes(strip_tags($_POST["job"]));
$list = array (
array('name', "$name"),
array('address', "$address"),
array('email', "$email"),
array('job', "$job"),
array(''),
array('options', 'status', 'link','time', 'note','check' )
);
// Merge the 2 arrays together
$final_array = array_merge($list, $_POST['prefs']);
// Send through CURL
post_to_url("http://192.168.10.10/receiver.php", $final_array);
header("Location:index.php");
exit;
}
?>
receiver:
<?php
$csv = fopen( "/home/user/file.csv", 'w+' );
foreach ($_POST as $fields) {
fputcsv($csv, $fields, ";");
}
fclose($csv);
?>
And now it works.
how to send multidimensional array post data in php?
I'm not sure why you pass your data as json_string
, but obviously a json string is considered a url_encoded string and decodes in what you get in your variables.
If json is not a requirement - you can pass your array directly to curl_setopt
or encode it with http_build_query
:
// passing raw array:
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
// passing query string:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
Post multidimensional array using CURL and get the result on server
cURL can only accept a simple key-value paired array where the values are strings, it can't take an array like yours which is an array of objects. However it does accept a ready made string of POST data, so you can build the string yourself and pass that instead:
$str = http_build_query($array);
...
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
A print_r($_POST)
on the receiving end will show:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 0
)
[2] => Array
(
[id] => 11
)
)
How to send a multidimensional array with PHP cURL without array keys from the nested arrays?
If you don’t want to write your own version of http_build_query, then I’d suggest you modify the version from this user comment in the manual, http://php.net/manual/en/function.http-build-query.php#111819
$query = http_build_query($query);
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
They are replacing foo[xy]
with foo[]
here - since you don’t want to keep the []
either, just replace '%5B%5D'
in the preg_replace call with an empty string instead.
How to Send Multidimensional Json array through php cURL
Try looking at the following example: POSTing JSON Data With PHP cURL
Useful excerpt:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
PHP Convert Multi-dimensional Array to Query String for curl POST
You can use http_build_query()
to create a string that you can pass to cURL:
<?php
$posted = ["foo"=>"bar", "address"=>["line1"=>"foo"]];
$string = http_build_query($posted);
echo $string;
Output:
foo=bar&address%5Bline1%5D=foo
You can also get access to the raw POST data using input://
but that is rarely necessary, unless dealing with non-HTML data.
PHP CURL Multidimensional/JSON Post
If you want to post exactly provided JSON sample, main error is in this line:
'Legs' => array ( ... ),
This code produce this JSON:
{"FirstOrder":{"Legs":{"Id":"0",...}},...}
instead of:
{"FirstOrder":{"Legs":[{"Id":"0",...}]},...}
Change the “Legs” line in this way:
'Legs' => array( array(
'Id' => '0',
'SecurityId' => '643',
'SecurityName' => 'AAPL',
'SecurityExchange' => 'NASDAQ national market',
'Side' => 'Buy',
'Quantity' => '100'
)),
Also (although I don't think that this can cause issues), if you want numbers encoded as numbers and booleans encoded as booleans, remove relative wrapping quotes:
'SymbolLastPrice' => 93.72,
(...)
'AllOrNone' => false,
(...)
'LimitOffset' => 0,
(...)
Related Topics
Generating Random Numbers Without Repeats
How to Use "Dependency Injection" in Simple PHP Functions, and Should I Bother
How to Sort an Array of Utf-8 Strings
Form Input Field Names Containing Square Brackets Like Field[Index]
Phpmyadmin - Count(): Parameter Must Be an Array or an Object That Implements Countable
Installing Specific Laravel Version with Composer Create-Project
How to Catch This Error: "Notice: Undefined Offset: 0"
How to Add Anchor Tag to a Url from Text Input
How to Access an Object Attribute That Starts with a Number
Fatal Error: Class 'Ziparchive' Not Found In
How to Use Open Id as Login System
Laravel 5.4 on PHP 7.0: Pdo Exception - Could Not Find Driver (Mysql)