Ако ви се наложи да изпратите многомерен масив и файлове едновременно, тази функция ще ви свърши работа. Тя "конверира" многомерния масив в едномерен, който може да бъде използван в curl_setopt функцията без да връща грешка (Array 2 string conversion while using CURLOPT_POSTFIELDS).
<?php
function buildCurlPostFields($data, $existingKeys = null, &$returnArray = [])
{
if ($data instanceof \CURLFile || !(is_array($data) || is_object($data))) {
$returnArray[$existingKeys] = $data;
return $returnArray;
} else {
foreach ($data as $key => $item) {
$this->buildCurlPostFields($item, $existingKeys ? $existingKeys . "[$key]" : $key, $returnArray);
}
return $returnArray;
}
}
Това е пълен пример как се използва фуннкцията:
<?php
$parameters = [
"name" => "Test",
"categories" => [
[
"id" => 1,
"name" => "Cat 1",
],
[
"id" => 2,
"name" => "Cat 1",
],
[
"id" => 3,
"name" => "Cat 1",
],
],
];
if (function_exists('curl_file_create')) { // php 5.5+
$cFile = curl_file_create(realpath($file), mime_content_type(realpath($file)), basename($file));
} else { //
$cFile = '@' . realpath($file);
}
$parameters["image"] = $cFile;
curl_setopt($ch, CURLOPT_URL, "https://example.com/post");
curl_setopt($ch, CURLOPT_POSTFIELDS, buildCurlPostFields($parameters));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: multipart/form-data',
]);
$output = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);










