PHP mySql数据到JSON文件 [英] PHP mySql data to JSON file

查看:176
本文介绍了PHP mySql数据到JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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:此示例引自谷歌

PS: this example is quoted from google

推荐答案

您可以使用json_encode函数.

  1. 从db获取数据并将其分配给数组
  2. 然后使用json_encode($result_array).这将产生json结果. 单击此处
  3. 使用file_put_contents函数将json结果保存到您的.json文件中
  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

以下是示例代码,

$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);

这篇关于PHP mySql数据到JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆