-2

I've got following JSON String:

{ email: "test@test.de", password: "123456" }

In my PHP File, i use following Code:

$content = file_get_contents("php://input");
$input = json_decode($content, true);


foreach ($input as $value) {
    $names[] = $value;

    $email = $value->email;
    $password = $value->password;

}

So how can i set a variable for the email and password?

Marcel
  • 381
  • 1
  • 5
  • 19
  • 4
    `$email = $input['email']` – Jonnix Mar 23 '17 at 09:35
  • Try `print_r($input)` to see the structure of the decoded data (It should be pretty obvious from the structure of the JSON but try it this way if reading the JSON doesn't help you). – axiac Mar 23 '17 at 09:38
  • @JonStirling Fantastic! Thank you :) – Marcel Mar 23 '17 at 09:39
  • 1
    Possible duplicate of [Parsing JSON file with PHP](http://stackoverflow.com/questions/4343596/parsing-json-file-with-php) – Marcel Mar 27 '17 at 20:22

2 Answers2

0

PHP code demo

There is no need for foreach.

$content = '{ "email": "test@test.de", "password": "123456" }';
$input = json_decode($content,true);


$email = $input["email"];
$password = $input["password"];

print_r($email);  //test@test.de
print_r($password); //123456
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

You can just refer to it in the following way:

$content = file_get_contents("php://input");
$input = json_decode($content, true);


foreach ($input as $value) {
    $names[] = $value;

    $email = $value['email'];
    $password = $value['password'];

}

Just an advice, please try to make sure that your variables' names give sense, so that it helps you understand more how to access it. for example it would be better if you use it this way:

$content = file_get_contents("php://input");
$inputs = json_decode($content, true);


foreach ($inputs as $input) {
    $names[] = $input;

    $email = $input['email'];
    $password = $input['password'];

}

This is better because you are going through all the inputs and at each one you get its email and password.

Alladin
  • 1,010
  • 3
  • 27
  • 45