• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 483
  • Last Modified:

Return JSON from php script

Hi,

I have a PHP script. I want to output a result as a JSON string/object. I'd like the output to look like this:

{
  "message": {
    "text": "Students fetched ok!",
  },
  "students": [
    {
      "student_id": "123",
      "student_name": "john doe"
    },
    {
      "student_id": "456",
      "student_name": "jane doe"
    }
  ]
}

not sure where to get started though. Looks like this is one big JSON object, which has a 'message' object, then an array of students (which I'll fetch from a database). What's a standard way people generate these types of responses from php scripts?

Thanks
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
1 Solution
 
nergikCommented:
hello

in php encoding json objects its really easy, you only need to:

echo json_encode($yourdata);

and php will convert your array in json format

for more info: php.net/json_encode
0
 
LordZardeckCommented:
Take your php array, and pass it to json_encode($array);.
For your example:
$array["Message"]["text"] = "Students fetched ok!";
$array["Students"] = array(array("student_id"=>"123", "student_name"=>"john doe"),array("student_id"=>"456", "student_name"=>"janedoe"));
echo json_encode($array);
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now