I am currently trying to localise my website and all the data is going to be stored in JSON file. So i want to know how to get the data using php
This is my sample JSON file/data
{
"en-us": {
"registration": {
"INVALID_USERNAME": "your username is taken",
"INVALID_PASSWORD": "your password is not strong",
"INVALID_EMAIL": "your email is invalid"
},
"login": {
"INVALID_USERNAME": "please enter your username",
"INVALID_PASSWORD": "please enter your password",
"INVALID_LOGIN": "username or password is wrong"
}
}
}
now how do i get the value INVALID_USERNAME from the registration section? I have tried this but it doesn't work.
$obj = json_decode(file_get_contents("en-us.json")); //file containing the json data above
echo $obj->{'INVALID_USERNAME'};
Sorry i am a newbie to php and JSON, thanks for your help in advance, Vidhu
3 Answers 3
You can try this one
$obj = json_decode(file_get_contents("en-us.json")); //file containing the json data above
echo $obj->{'en-us'}->{'registration'}->{'INVALID_USERNAME'};
Comments
As a solution to your problem please try executing below code snippet
<?php
$json_content=file_get_contents("en-us.json");
$json_array=json_decode($json_content,true);
if(!empty($json_array))
{
echo $json_array['en-us']['registration']['INVALID_USERNAME'];
}
?>
Comments
You're correct in doing:
$obj = json_decode(file_get_contents("en-us.json"));
To get INVALID_USERNAME you need to do:
$obj->en_us->registration->INVALID_USERNAME
This is because INVALID_USERNAME is a property within the object registration, which is a property under the object en_us.