PHP mySql数据到JSON文件

Daf*_*Dev 0 php mysql sql json converter

因此,我需要通过php查询我的数据库,然后将查询转换为.json文件以使用Google Charts.

我如何通过PHP将mysql查询转换为.json文件,如下所示:

{
  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!'}
}
Run Code Online (Sandbox Code Playgroud)

PS:这个例子是从谷歌引用的

Nik*_*han 9

你可以使用json_encode功能.

  1. 从db获取数据并将其分配给数组
  2. 然后用json_encode($result_array).这将产生json结果.点击这里
  3. 使用file_put_contents函数将json结果保存到.json文件中

以下是一个示例代码,

$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);
Run Code Online (Sandbox Code Playgroud)