簡體   English   中英

PHP mySql數據到JSON文件

[英]PHP mySql data to JSON file

因此,我需要通過php查詢數據庫,然后將查詢轉換為.json文件以使用Google圖表

我如何通過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

您可以使用json_encode函數。

  1. 從數據庫獲取數據並將其分配給數組
  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);

使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM