【问题标题】:PHP export to CSV instead of JSON [duplicate]PHP导出到CSV而不是JSON [重复]
【发布时间】:2017-03-03 15:24:56
【问题描述】:

我有将记录导出为 JSON 的工作代码(请参见下文),现在我需要将记录导出为 CSV。 下面的代码具有“根节点”,这意味着它将导出 PARENTID=2 的成员及其所有子节点(递归)。 我需要的是导出的是给定 PARENTID 的记录,但以 CSV 格式而不是 JSON 格式。

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydataabse";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    $index = array();
    $sql = "SELECT NAME, ID, PARENTID FROM mytable";
    $result = $conn->query($sql);

    while($row = $result->fetch_array(MYSQLI_ASSOC)){
      $rows[] = $row;
      $index[$row['ID']] = $row;
    }

    // build the tree
    foreach($index as $id => &$row){
      if ($id === 0) continue;
      $parent = $row['PARENTID'];
      $index[$parent]['children'][] = &$row;
    }
    unset($row);

    // root node - exported are members with this PARENTID and all they children's
    $index = $index[2]['children'];

    /* free result set */
    $result->close();
    /* close connection */
    $conn->close();

    // output json
    header('Content-Type: application/json');
    echo json_encode($index, JSON_PRETTY_PRINT);

如果需要,这里是 mytable 结构:

ID  PARENT    NAME
1     0       John Doe
2     1       Sally Smith
3     2       Mike Jones
4     3       Jason Williams
5     4       Sara Johnson
6     1       Dave Wilson
7     2       Amy Martin

非常感谢。

【问题讨论】:

    标签: php mysqli export-to-csv


    【解决方案1】:

    你可以像这样使用原生函数fputcsv

    编辑:在您的代码中包含一个完整示例

    <?php
    
    $rows = array(
    array('id' => 1, 'Parent' => 0, 'name' => 'John Doe'),
    array('id' => 2, 'Parent' => 1, 'name' => 'Sally Smith'),
    array('id' => 3, 'Parent' => 2, 'name' => 'Mike Jones'),
    array('id' => 4, 'Parent' => 3, 'name' => 'Jason Williams'),
    array('id' => 5, 'Parent' => 4, 'name' => 'Sara Johnson'),
    array('id' => 6, 'Parent' => 1, 'name' => 'Dave Wilson'),
    array('id' => 7, 'Parent' => 2, 'name' => 'Amy Martin'),
    );
    // create an index on id
    $index = array();
    
    foreach($rows as $row){
      $index[$row['id']] = $row;
    }
    
    // build the tree
    foreach($index as $id => &$row){
      if ($id === 0) continue;
      $parent = $row['Parent'];
      $index[$parent]['children'][] = &$row;
    }
    unset($row);
    
    // obtain root node
    $index = $index[2]['children'];
    
    // Construct the final datas
    $columns = array('Name', 'Id', 'ParentID');
    
    $datas = array($columns);
    foreach($index as $data) {
        $datas[] = array(
            $data['name'],
            $data['id'],
            $data['Parent']
    
        );
    }
    
    // Tell the client to download file
    headerDownload('mySuperFile.csv');
    
    // Export the CSV to standard output
    exportToCSV('php://output', $datas);
    
    function exportToCSV($file, array $values, $delimiter = ";", $enclosure = '"', $escape = "\\")
    {
        $handler = @fopen($file, 'w');
    
        if(! $handler) {
            throw new Exception(sprintf("Unable to open stream '%s'", $file));
        }
    
        foreach ($values as $value) {
            fputcsv($handler, $value, $delimiter, $enclosure, $escape);
        }
        return fclose($handler);
    }
    
    function headerDownload($filename)
    {
        // disable caching
        $now = gmdate("D, d M Y H:i:s");
        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
    
        // force download
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
    
        // disposition / encoding on response body
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");
    }
    

    【讨论】:

    • 非常感谢,但我需要把这段代码放在哪里?我是 PHP 新手,如果您能编写包含上述代码的简单示例,我将不胜感激。
    • 我刚刚编辑了我的回复。你能检查它是否工作吗?不是,尝试注释行 headerDownload('mySuperFile.csv');并告诉我输出
    • 您好,非常感谢,这里有错误:
      警告:array_unshift() 期望参数 1 为数组,C 中给出 null: \Apps\CSV.php74 行

      可捕获的致命错误:传递给 exportToCSV() 的参数 2 必须是类型数组,给定空值,在第 76 行的 C:\Apps\CSV.php 中调用,并在第 39 行的 C:\Apps\CSV.php 中定义
    • 我认为您的代码存在错误。当您执行 $index = $index[2]['children']; 时,您确定 $index 变量是一个数组吗? ? JSON 版本是否有效?
    • 您好,是的,它有效,这是您可以查看的简单版本:code.reloado.com/oeasyrik1/83/edit
    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2011-08-09
    • 2016-02-05
    相关资源
    最近更新 更多