0

Hi I'm working on a simple, universal REST API to read the first name and email address from a JSON POST call I'm using a sample test POST to pass these values across to the script.

{
    "fname": "Viktor",
    "email": "sample@emailhere.net"
}

Here's the code

$json = file_get_contents('php://input');
$data = json_decode($json);
print_r ($data);

it works fine and returns

stdClass Object ( [fname] => Ram [email] => Ram@gmail.com )

...but when I try to extract a specific element from the $data it returns a 500 server error - i.e. I added these 3 lines

$email = $data[0]["email"];
$fname = $data[0]["fname"];
print "email: $email fname: $fname";

What is the correct syntax to extract this simple JSON?

Viktor
  • 517
  • 5
  • 23

1 Answers1

1

Your JSON is not an array. Plus, json_decode returns object by default, you need to set it to associative array mode. Correct code will be

$json = file_get_contents('php://input');
$data = json_decode($json, true);
$email = $data["email"];
$fname = $data["fname"];
print "email: $email fname: $fname";
nikserg
  • 382
  • 1
  • 11