John Davidson

Post php array with Guzzle

0 comments
Message:


I know how to send post requests with Guzzle.
Here is an example oh what I’m used to do :


$response = $client->request('POST', $uri, [
'exceptions' => false,
'debug' => false,
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 30,
'json' => [
data_1 => $data_1,
data_2 => $data_2,
data_3 => $data_3,
]
]);

However, I am having a problem sending a php array.


My array php is :


Array
(
[lorem_1] => Array
(
[data_1] => 1189
[data_2] => 100
[data_3] => 110
[data_4] => 120
)

[lorem_2] => Array
(
[data_1] => 54
[data_2] => 130
[data_3] => 140
[data_4] => 150
)

)

This is what I need to send. It is working in postman :


[
{
"data_1": "1189",
"data_2": "100",
"data_3": "110",
"data_4": "120"
},
{
"data_1": "54",
"data_2": "130",
"data_3": "140",
"data_4": "150"
}
]

So, I just need to convert my php array to something acceptable by Guzzle.


I’ve tested of course :


$response = $client->request('POST', $uri, [
'exceptions' => false,
'debug' => false,
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 30,
'json' => $my_array
]);

But it doesn't work.


I’ve tested :


$response = $client->request('POST', $uri, [
'exceptions' => false,
'debug' => false,
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 30,
'json' => array_values($my_array),
]);

But it doesn't work


I’ve tested :


$response = $client->request('POST', $uri, [
'exceptions' => false,
'debug' => false,
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 30,
'json' => json_encode(array_values($my_array))
]);

But it doesn't work. The json is valid and works in Postman but not in Guzzle. I guess it is a simple syntax issue or array format but I don’t know.


Do you know what to do ?



My Answer:
>request('POST', 'https://api.example.com', [
'json' => [
'key1' => 'value1',
'key2' => 'value2'
]
]);

This code sends a POST request to https://api.example.com with a JSON body containing key-value pairs 'key1' => 'value1' and 'key2' => 'value2'. You can modify the key-value pairs as needed for your specific use case.

Rate this post

3 of 5 based on 8437 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us