Pages

Wednesday, October 19, 2011

How to create json From PHP


JSON stands for JavaScript Object Notation is a subset of the object literal notation of JavaScript. Since it can be used in javascript with no muss or fuss. Below is the example of JSON :
var myObject = {nations: [
        {name: "England", continent: "Europe"},
        {name: "USA", continent: "America"},
        {name: "JAPAN", continent: "Asia"}
    ]
};
This posting will discuss about creating JSON from PHP-Mysql Database driven application. The following is the step to do that :
  1. Get Data from database.
    For example we have table "country" contains two columns name, and continent. So, we need to query data.
    $query = "select * from country";
    $parse = mysql_query($query);
    while($row = mysql_fetch_object($result)){
       $result[] = $row;
    }
    
  2. Convert data to json
  3. var myString = '<?php json_encode($result);?>';
    
  4. Create json object
  5. var myObject = eval('(' + myString + ')');
  6. Check JSON
    That's it. JSON already created

No comments:

Post a Comment

Don't Forget To Join Our Community
×
Widget