【问题标题】:PHP mySql data to JSON filePHP mySql 数据到 JSON 文件
【发布时间】:2013-06-23 10:35:55
【问题描述】:

所以,我需要通过 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!'}
}

PS:本例引自google

【问题讨论】:

    标签: php mysql sql json converter


    【解决方案1】:

    使用mysql_fetch_object将mysql表转换为php对象,然后使用json_encode转换为json

    mysql_fetch_object 获取行。所以使用循环来构造一个表对象。

    代码:

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

    【讨论】:

      【解决方案2】:

      你可以使用json_encode函数。

      1. 从 db 中获取数据并将其分配给数组
      2. 然后使用json_encode($result_array)。这将产生 json 结果。 Click here
      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);
      

      【讨论】:

      • 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
      猜你喜欢
      • 2014-04-08
      • 2013-12-08
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多