0

So, i need to query my database by php and then convert the query into a .json file to use Google Charts.

How can i convert a mysql query through PHP to a .json file somewhat like this:

{
  cols: [{id: 'A', label: 'NEW A', type: 'string'},
         {id: 'B', label: 'B-label', type: 'number'},
         {id: 'C', label: 'C-label', type: 'date'}
        ],
  rows: [{c:[{v: 'a'}, {v: 1.0, f: 'One'}, {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}]},
         {c:[{v: 'b'}, {v: 2.0, f: 'Two'}, {v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}]},
         {c:[{v: 'c'}, {v: 3.0, f: 'Three'}, {v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}]}
        ],
  p: {foo: 'hello', bar: 'world!'}
}

PS: this example is quoted from google

2 Answers 2

11

You can use json_encode function.

  1. Fetch data from db and assign it to an array
  2. Then use json_encode($result_array). This will produce the json result. Click here
  3. Use file_put_contents function to save the json result to your .json file

Following is an example code,

$result = mysql_query(your sql here);    
$data = array();
while ($row = mysql_fetch_assoc($result)) {
    // Generate the output in desired format
    $data = array(
        'cols' => ....
        'rows' => ....
        'p' => ...
    );
}

$json_data = json_encode($data);
file_put_contents('your_json_file.json', $json_data);
Sign up to request clarification or add additional context in comments.

1 Comment

exactly.get the result from json_encode($array) and send it to a .json file so i can get it later to output in a google chart
1

convert mysql table to php object using mysql_fetch_object and then to json with json_encode

mysql_fetch_object fetches row. so use loop to construct a table object.

code:

$result = mysql_query("select * from mytable");
$table=array();
while($row=$mysql_fetch_object($result)){
  $table.push($row);
  unset($row);
}
echo json_encode($table);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.