Andi Andi - 1 month ago 8
JSON Question

Use json_encode() for JSON representation of a value in php file

I need help to properly use json_encode() to return a JSON representation of a value in my php server script. As far as i learned, this is not done with echo, print or loop as explained in all the other questions i studied before asking.

How do i get one "Value" from my data.json file

{
"clientPrivateKey": {
"Name":"AWS_CLIENT_SECRET_KEY",
"Value":"someexammplestring"
},
"serverPublicKey": {
"Name":"AWS_SERVER_PUBLIC_KEY",
"Value":"someexammplestring"
},
"serverPrivateKey": {
"Name":"AWS_SERVER_PRIVATE_KEY",
"Value":"someexammplestring"
},
"expectedBucketName": {
"Name":"S3_BUCKET_NAME",
"Value":"someexammplestring"
}
}


into the corresponding PHP variable in my php server script?

$clientPrivateKey =
$serverPublicKey =
$serverPrivateKey =
$expectedBucketName =


I only need the "Value" string here. The value is supposed to give a valid JSON response inside the php server script calculating signatures or else it will {"invalid":true}. Thanx for your help!

Answer Source

To get the data from a JSON file, you use json_decode(), not json_encode(). Then you access the parts of it using normal PHP object syntax.

$json = file_get_contents("data.json");
$data = json_decode($json);
$clientPrivateKey = $data->clientPrivateKey->Value;
$serverPublicKey = $data->serverPublicKey->Value;
$serverPrivateKey = $data->serverPrivateKey->Value;
$expectedBucketName = $data->expectedBucketName->Value;