5

After a long day of debugging and try and error tries searching for a good method with Guzzle6 post with nested array and resource items.

I've found on Guzzle6 documentation that data need to be post with ['multipart' => []]. This works when i got single array items. But i got nested array items like this.

[
    [firstname] => 'Danny',
    [phone] => [
        [0] => [
            [phone] => 0612345678
        ]
    ]
    [picture] => '/data/...'
]

This needs to be format as multipart for Guzzle6 as below.

[
    [
        'name' => 'firstname',
        'contents' => 'Danny'
    ],
    [
        'name' => 'phone[0][phone]
        'contents' => '0612345678'
    ],
    [
        'name' => 'picture',
        'contents' => fopen('....', 'r')
    ]
]

I want to fix this without special tricks. Is there a good way to send a post array with nested array and resource to multipart array.

Danny Bevers
  • 831
  • 1
  • 8
  • 16
  • So you basically want to make a loop that iterates over every key and creates a new array in the multipart format –  Jan 11 '17 at 13:04

8 Answers8

9

After a full day of work i got my multipart form data array. For everyone with the same problem here's the code. In $output there's a array of fields within data. It can be used in ['multipart' => $output] with Guzzle.

    $output = [];

    foreach($data as $key => $value){
        if(!is_array($value)){
            $output[] = ['name' => $key, 'contents' => $value];
            continue;
        }

        foreach($value as $multiKey => $multiValue){
            $multiName = $key . '[' .$multiKey . ']' . (is_array($multiValue) ? '[' . key($multiValue) . ']' : '' ) . '';
            $output[] = ['name' => $multiName, 'contents' => (is_array($multiValue) ? reset($multiValue) : $multiValue)];
        }
    }
Danny Bevers
  • 831
  • 1
  • 8
  • 16
4

I used @DannyBevers answer above, but discovered that it doesn't work for deeply nested arrays that need to be sent as multipart, so here is an alternative solution:

// fake nested array to be sent multipart by guzzle
$array = array(
        'title' => 'Test title',
        'content' => 'Test content',
        'id' => 17,
        'Post' => array(

                0 => array(
                        'id' => 100027,
                        'name' => 'Fake post title',
                        'content' => 'More test content ',
                        'Comments' => array (

                                0 => 'My first comment',
                                1 => 'My second comment',
                                2 => 'My third comment'
                        )
                ),
                1 => array(
                        'id' => 100028,
                        'name' => 'Another fake post title',
                        'overall' => 2,
                        'content' => 'Even More test content ',
                        'Comments' => array (

                                0 => 'My other first comment',
                                1 => 'My other second comment',

                        )
                )

        )
);


$flatten = function($array, $original_key = '') use (&$flatten) {

    $output = [];

    foreach ($array as $key => $value) {

        $new_key = $original_key;

        if (empty($original_key)) {

            $new_key .= $key;

        } else {

            $new_key .= '[' . $key . ']';

        }

        if (is_array($value)) {

            $output = array_merge($output, $flatten($value, $new_key));

        } else {

            $output[$new_key] = $value;

        }
    }

    return $output;

};


$flat_array = $flatten($array);

$data = [];

foreach($flat_array as $key => $value) {

    $data[] = [

            'name'  => $key,
            'contents' => $value

    ];


}

$response = $guzzle->request($type, $get, array('multipart' => $data));
John
  • 486
  • 5
  • 15
4

@see https://github.com/guzzle/guzzle/issues/1679#issuecomment-342233663

Use http_build_query to get flatten names and then built up multipart.

$multipart = [];
$vars = explode('&', http_build_query($postData));
foreach ($vars as $var) {
    list($nameRaw, $contentsRaw) = explode('=', $var);
    $name = urldecode($nameRaw);
    $contents = urldecode($contentsRaw);
    $multipart[] = ['name' => $name, 'contents' => $contents];
}
Steffen Mächtel
  • 981
  • 8
  • 13
2

As I was stuck with the exactly same issue and as I get collection field, I have a multi-nested-level-array ! So,I needed to adapt functions posted here.

I merged @John and @DannyBevers solutions to obtain a full key for name param and just the value for contents param. Then, I added the function result under the multipart key

FUNCTION :

private function flatten($array, $prefix = "[", $suffix = "]") {
    global $i;
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            if($i == 0) {
                $result = $result + $this->flatten($value, $key.$prefix, $suffix);
            }
            else {
                foreach ($this->flatten($value, $prefix . $key . $suffix."[", $suffix) as $k => $v){
                    $result[] = $v;
                }
            }
        }
        else {                
            if($value instanceof UploadedFile){
                $result[] = ["name" => $prefix.$key.$suffix,
                    "filename" => $value->getClientOriginalName(),
                    "Mime-Type" => $value->getMimeType(),
                    "contents" => fopen($value->getPathname(), "r")];
            }
            else {
                $result[] = ["name" => $prefix . $key . $suffix, "contents" => $value];
            }
        }
        $i++;
    }
    return $result;
}

OUTPUT :

Array
(
    [multipart] => Array
        (
            [0] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[sessionType]
                    [contents] => 1
                )
            [1] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[globalServiceType]
                    [contents] => 1
                )
            [2] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[brand]
                    [contents] => 1
                )
            [3] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[device]
                    [contents] => 1
                )
            [4] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[interfaces][0]
                    [contents] => 1
                )
            [5] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[interfaces][1]
                    [contents] => 1
                )
            [6] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][0][application]
                    [contents] => 6
                )
            [7] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][0][quantity]
                    [contents] => 2
                )
            [8] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][2][application]
                    [contents] => 2
                )
            [9] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][2][quantity]
                    [contents] => 3
                )
            [10] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][5][application]
                    [contents] => 5
                )
            [11] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][5][quantity]
                    [contents] => 5
                )
            [12] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[trackingNumber]
                    [contents] => CPV_XXXX
                )
            [13] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyAddress]
                    [contents] => street
                )
            [14] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyCity]
                    [contents] => Caen
                )
            [15] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyCountry]
                    [contents] => AF
                )
            [16] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyFax]
                    [contents] => 
                )
            [17] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyName]
                    [contents] => Society
                )
            [18] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyPhone]
                    [contents] => 0233445566
                )
            [19] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyPostalCode]
                    [contents] => 14000
                )
            [20] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyState]
                    [contents] => 
                )
            [21] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][email]
                    [contents] => john@mail.fr
                )
            [22] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][fullName]
                    [contents] => John
                )
            [23] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[platformImport]
                    [contents] => 1
                )
            [24] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[standardProfileImport]
                    [contents] => 1
                )
            [25] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[technicalContact][email]
                    [contents] => patou@mail.fr
                )
            [26] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[technicalContact][fullName]
                    [contents] => Patou
                )
            [27] => Array 
                (
                    [name] => requestbundle_issuingserviceproduct[filesForm][0][binaryContent]
                    [filename] => "File_test_to_upload.txt"
                    [Mime-Type] => "text/plain"
                    [contents] => stream resource @28{
                            timed_out: false
                            blocked: true
                            eof: false
                            wrapper_type: "plainfile"
                            stream_type: "STDIO"
                            mode: "r"
                            unread_bytes: 0
                            seekable: true
                            uri: "/tmp/phpEgxr10"
                            options: []
                                                  }
              )
        )
)

@Danny Bevers solution will output :

Array
(
    [multipart] => Array
        (
            [0] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[sessionType]
                    [contents] => 1
                )

            [1] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[globalServiceType]
                    [contents] => 1
                )    
            [2] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[brand]
                    [contents] => 1
                )    
            [3] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[device]
                    [contents] => 1
                )    
            [4] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[interfaces][0]
                    [contents] => 1
                )    
            [5] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[applicationsProductQuantity][0]
                    [contents] => Array
                        (
                            [application] => 6
                            [quantity] => 2
                        )

                )    
            [6] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[trackingNumber]
                    [contents] => CPV_XXXX
                )
            [7] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[billingContact][companyAddress]
                    [contents] => street
                )   
            [8] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[platformImport]
                    [contents] => 1
                )   
            [9] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[standardProfileImport]
                    [contents] => 1
                )

            [10] => Array
                (
                    [name] => requestbundle_issuingserviceproduct[technicalContact][email]
                    [contents] => patou@mail.fr
                )

        )

)

Inside my project, my function does not throw any error while @DannyBevers's does.

Hope it will help !

Delphine
  • 861
  • 8
  • 21
1

Example Data:

$array = [
  "doc_id" => 2,
  "data" => [
    [
      "field" => "10"
      "value" => "test10"
    ],
    [
      "field" => "11"
      "value" => "test11"
    ]
  ]
]

Encode Multidimensial Array

$outputArray = explode('&', urldecode(http_build_query($array)))

Output:

array[
  0 => "doc_id =2",
  1 => "data[0][field]=10",
  2 => "data[0][value]=test10",
  3 => "data[1][field]=11",
  4 => "data[1][value]=test11"
]

Add Post Data:

foreach ($outputArray as $data) {
    list($key, $value) = explode('=', $data);
    $postData[] = ['name' => $key, 'contents' => $value];
}
Cesur APAYDIN
  • 806
  • 3
  • 11
  • 24
0

take pretty function for it:

function getFlatten($key, array $data, $result = [])
{
    foreach ($data as $subKey => $value) {
        $subKey = $key . '[' . $subKey . ']';
        if (\is_array($value)) {
            $result = $this->getFlatten($subKey, $value, $result);
        } else {
            $result[] = ['name' => $subKey, 'contents' => $value];
        }
    }

    return $result;
}

Example

   $data = [
        'first' => [
            'second' => ['third' => 12, 'third_a' => 13],
            'second_2' => 3,
            'second_3' => ['third_2' => ['fours' => 15]],
        ],
    ];

if (is_array($data)) {
    $request = getFlatten('main_key', $data)
}

Output

    0 => [
        'name' => 'main_key[first][second][third]'
        'contents' => 12
    ]
    1 => [
        'name' => 'main_key[first][second][third_a]'
        'contents' => 13
    ]
    2 => [
        'name' => 'main_key[first][second_2]'
        'contents' => 3
    ]
    3 => [
        'name' => 'main_key[first][second_3][third_2][fours]'
        'contents' => 15
    ]
vladnev
  • 101
  • 5
0

None of the above solutions worked for me as my array structure had top level values as well as nested.

I created this Gist which solved the problem: https://gist.github.com/matthew-inamdar/a17701f948770ac0a55acd9d12445645

You can simply use follows:

$data = [
    'name' => 'John',
    'language' => [
        'main' => 'English',
        'secondary' => [
            0 => 'Spanish',
            1 => 'German'
        ]
    ],
];

$flattened = (new Flatten())->flatten($data);

$flattened = [
    ['name' => 'name', 'contents' => 'John'],
    ['name' => 'language[main]', 'contents' => 'English'],
    ['name' => 'language[secondary][0]', 'contents' => 'Spanish'],
    ['name' => 'language[secondary][1]', 'contents' => 'German']
];
Matt Inamdar
  • 136
  • 10
-1

Yes, there is a simpler method. You can send the values as an array in your desired format and combine them using http_build_query.

Example:

$params = [
    'firstname' => 'Danny',
    'phone' => [
            'phone' => '0612345678'
               ]
    'picture' => '/data/...'
]


$request_pararms = http_build_query($params);

now send the $request_params in the Guzzle.

Arun Code
  • 1,548
  • 1
  • 13
  • 18