使用php pdo将JSON转换为Excel文件

时间:2015-05-15 12:48:01

标签: php mysql json excel pdo

我有这个文件,它给我来自mysql数据库的JSON输出:

<?php

require 'core/init.php';
$general->logged_out_protect();

$username   = htmlentities($user['username']); 
$user_id  = htmlentities($user['id']);


    try {


      $result = $db->prepare('SELECT ID,br,sufiks,kupac,datum,rok,status FROM racuni WHERE user_id=:user_id');
      $result->bindParam(':user_id', $user_id); 
      $result->execute();
      //$res = $result->fetchAll(PDO::FETCH_ASSOC);

        /* Extract the information from $result */
        foreach($result as $r) {
          $temp = array();
          // the following line will be used to slice the Pie chart
          $temp['ID'] =  (int) $r['ID']; 
          $temp['br'] = $r['br'].$r['sufiks'];

          $temp['kupac'] = (string) $r['kupac'];
          $temp['datum'] = (string) $r['datum'];
          $temp['rok'] = (string)$r['rok'];
          $temp['status'] = (string)$r['status'];

               //   $rs = $db->prepare('SELECT sum(radnih_sati) FROM track_radnici WHERE user_id=:user_id AND id_radnika=:id');
         // $rs->bindParam(':user_id', $user_id); 
        //  $rs->bindParam(':id', $r['ID']);
          //$rs->bindParam(':radnici', $radnici); 
         // $rs->execute();
        //  $sumRows = $rs->fetchColumn(); 
        //  $temp['7'] = (int) $sumRows;



          // Values of each slice

          $rows[] = $temp;
        }


    $table['data'] = $rows;


        $jsonTable = json_encode($table);

    //echo $jsonTable;
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;


    ?>

一切都很好,这段代码给了我这个输出:

{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}

如何将此JSON输出转换为Excel文件?做这个的最好方式是什么?或者其他一些没有JSON的方式?你的建议是什么?

1 个答案:

答案 0 :(得分:1)

这与您的请求有所不同,因为它不涉及JSON

如果您希望它出类拔萃,您只需使用INTO OUTFILE并生成Excel可以阅读的csv即可。也许你真的需要.xlsx文件?

实施例

SELECT ID,br,sufiks,kupac,datum,rok,status 
INTO OUTFILE 'C:/excel.csv'
CHARACTER SET latin1
FIELDS TERMINATED BY '\t' -- this is tab separated
LINES TERMINATED BY '\r\n'
FROM racuni WHERE user_id=:user_id;

如果你想要列出现,你必须在SELECT之前添加这一行。

SELECT 'ID','br','sufiks','kupac','datum','rok','status' 
UNION
SELECT ID,br,sufiks,kupac,datum,rok,status 
INTO OUTFILE 'C:/excel.csv'
CHARACTER SET latin1
FIELDS TERMINATED BY '\t' -- this is tab separated
LINES TERMINATED BY '\r\n'
FROM racuni WHERE user_id=:user_id;

我不确定它会起作用,但试一试。

$result = $db->prepare('SELECT ''ID'',''br'',''sufiks'',''kupac'',''datum'',''rok'',''status'' 
    UNION
    SELECT ID,br,sufiks,kupac,datum,rok,status 
    INTO OUTFILE ''C:/excel.csv''
    CHARACTER SET latin1
    FIELDS TERMINATED BY ''\t''
    LINES TERMINATED BY ''\r\n''
    FROM racuni WHERE user_id=:user_id;');
      $result->bindParam(':user_id', $user_id); 
      $result->execute();

那么迭代最不可能不需要?