Home > Net >  PHP Extract Values from JSON Array for REST API [duplicate]
PHP Extract Values from JSON Array for REST API [duplicate]

Time:09-17

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": "[email protected]"
}

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] => [email protected] )

...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?

CodePudding user response:

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";
  • Related