I am sending over the below payload from Postman to a PHP endpoint using a POST:
{
"email": "myemail@yahoo.com",
"overwrite": true,
"fields": {
"first_name": "John Doe",
"country": "Chile",
"mrc_c3": "25.00",
"mrc_date_c3": "10/10/24"
}
}
Over in the PHP script, I have the below code:
<?php
require_once("db.php");
$payload = json_decode(file_get_contents("php://input"), true)["payload"];
echo "this is the payload: " . $payload[];
?>
As you see in the above, I attempted to just echo out the payload array, but Postman is only printing out "this is the payload" and nothing else.
How can I edit the above code so that it displays the payload that I sent from Postman?
I see two problems:
First, you're referencing an array key named payload
but you don't have any key named that:
$payload = json_decode(file_get_contents("php://input"), true)["payload"];
^^^^^^^
You probably just want to decode the body as a whole:
$payload = json_decode(file_get_contents("php://input"), true);
Then you'll get:
echo $payload['email']; // myemail@yahoo.com
echo $payload['fields']['country']; // Chile
Second, using the array braces here is a syntax error:
echo "this is the payload: " . $payload[];
^^
If you want to refer to the whole array, just use $payload
by itself. However, note that you can't just echo
an array, as echo
is for scalar values only. You could do:
$payload = json_decode(file_get_contents("php://input"), true);
print_r($payload);
And you'll get:
Array
(
[email] => myemail@yahoo.com
[overwrite] => 1
[fields] => Array
(
[first_name] => John Doe
[country] => Chile
[mrc_c3] => 25.00
[mrc_date_c3] => 10/10/24
)
)