代码之家  ›  专栏  ›  技术社区  ›  Jason

在PHP中为用户创建CSV文件

  •  207
  • Jason  · 技术社区  · 17 年前

    我有MySQL数据库中的数据。我正在向用户发送一个URL,以将其数据作为CSV文件输出。

    当他们点击链接时,我怎么能弹出窗口从MySQL下载带有记录的CVS?

    我已经掌握了获取记录的所有信息。我只是不知道如何让PHP创建CSV文件并让他们下载扩展名为.CSV的文件。

    20 回复  |  直到 12 年前
        1
  •  476
  •   ntzm    7 年前
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    
    function outputCSV($data) {
      $output = fopen("php://output", "wb");
      foreach ($data as $row)
        fputcsv($output, $row); // here you can change delimiter/enclosure
      fclose($output);
    }
    
    outputCSV(array(
      array("name 1", "age 1", "city 1"),
      array("name 2", "age 2", "city 2"),
      array("name 3", "age 3", "city 3")
    ));
    

    php://output
    fputcsv

        2
  •  289
  •   Popnoodles    9 年前

    尝试:

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    echo "record1,record2,record3\n";
    die;
    

    编辑:下面是一段代码片段,我可以选择对CSV字段进行编码:

    function maybeEncodeCSVField($string) {
        if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
            $string = '"' . str_replace('"', '""', $string) . '"';
        }
        return $string;
    }
    
        3
  •  19
  •   ntzm    7 年前

    下面是@Andrew发布的php.net函数的改进版本。

    function download_csv_results($results, $name = NULL)
    {
        if( ! $name)
        {
            $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
        }
    
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename='. $name);
        header('Pragma: no-cache');
        header("Expires: 0");
    
        $outstream = fopen("php://output", "wb");
    
        foreach($results as $result)
        {
            fputcsv($outstream, $result);
        }
    
        fclose($outstream);
    }
    

    它非常易于使用,并且与MySQL(i)/PDO结果集配合使用非常好。

    download_csv_results($results, 'your_name_here.csv');
    

    记住 exit()

        4
  •  16
  •   Stan    11 年前

    除上述内容外,您可能还需要添加:

    header("Content-Transfer-Encoding: UTF-8");
    

    它在处理包含多种语言的文件时非常有用,例如人名或城市。

        5
  •  9
  •   LBJ    14 年前

    我知道这条线索有点旧,但为了将来的参考和我自己:

    <a href="my_csv_creator.php?user=23&amp;othervariable=true">Get CSV</a>
    

    User_John_Doe_10_Dec_11.csv
    
        6
  •  8
  •   ntzm    7 年前

    创建您的文件,然后返回对该文件的引用以及正确的标题,以触发另存为-根据需要编辑以下内容。将CSV数据放入$csvdata。

    $fname = 'myCSV.csv';
    $fp = fopen($fname,'wb');
    fwrite($fp,$csvdata);
    fclose($fp);
    
    header('Content-type: application/csv');
    header("Content-Disposition: inline; filename=".$fname);
    readfile($fname);
    
        7
  •  5
  •   ntzm    7 年前

    以下是使用PDO并包括列标题的完整工作示例:

    $query = $pdo->prepare('SELECT * FROM test WHERE id=?');
    $query->execute(array($id));    
    $results = $query->fetchAll(PDO::FETCH_ASSOC);
    download_csv_results($results, 'test.csv'); 
    exit();
    
    
    function download_csv_results($results, $name)
    {            
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename='. $name);
        header('Pragma: no-cache');
        header("Expires: 0");
    
        $outstream = fopen("php://output", "wb");    
        fputcsv($outstream, array_keys($results[0]));
    
        foreach($results as $result)
        {
            fputcsv($outstream, $result);
        }
    
        fclose($outstream);
    }
    
        8
  •  4
  •   Behzad Ravanbakhsh    15 年前

    首先将数据设置为字符串,逗号作为分隔符(以“,”分隔)。像这样的

    $CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine
    
    $rand = rand(1,50); //Make a random int number between 1 to 50.
    $file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server 
                                         //side it is recommended that the file name be different.
    
    file_put_contents($file,$CSV_string);
    
    /* Or try this code if $CSV_string is an array
        fh =fopen($file, 'w');
        fputcsv($fh , $CSV_string , ","  , "\n" ); // "," is delimiter // "\n" is new line.
        fclose($fh);
    */
    
        9
  •  3
  •   Kaddy    13 年前

    嘿,它工作得很好。。。。!!!!谢谢Peter Mortensen和Connor Burton

    <?php
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    ini_set('display_errors',1);
    $private=1;
    error_reporting(E_ALL ^ E_NOTICE);
    
    mysql_connect("localhost", "user", "pass") or die(mysql_error());
    mysql_select_db("db") or die(mysql_error());
    
    $start = $_GET["start"];
    $end = $_GET["end"];
    
    $query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
    $select_c = mysql_query($query) or die(mysql_error());
    
    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        $result.="{$row['email']},";
        $result.="\n";
        echo $result;
    }
    

    ?>

        10
  •  2
  •   ntzm    7 年前

    $data = array (
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"');
    
    $fp = fopen('data.csv', 'wb');
    foreach($data as $line){
        $val = explode(",",$line);
        fputcsv($fp, $val);
    }
    fclose($fp);
    

    所以每行 $data 数组将转到新创建的CSV文件的新行。它只适用于PHP5及更高版本。

        11
  •  2
  •   ntzm    7 年前

    您只需使用以下命令将数据写入CSV fputcsv

    $list[] = array("Cars", "Planes", "Ships");
    $list[] = array("Car's2", "Planes2", "Ships2");
    //define headers for CSV 
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=file_name.csv');
    //write data into CSV
    $fp = fopen('php://output', 'wb');
    //convert data to UTF-8 
    fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
    foreach ($list as $line) {
        fputcsv($fp, $line);
    }
    fclose($fp);
    
        12
  •  1
  •   Sergiu    15 年前

    最简单的方法是使用专用的 CSV class 这样地:

    $csv = new csv();
    $csv->load_data(array(
        array('name'=>'John', 'age'=>35),
        array('name'=>'Adrian', 'age'=>23), 
        array('name'=>'William', 'age'=>57) 
    ));
    $csv->send_file('age.csv'); 
    
        13
  •  1
  •   Peter Mortensen Pieter Jan Bonestroo    15 年前

    而不是:

    $query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
    $select_c = mysql_query($query) or die(mysql_error()); 
    
    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        $result.="{$row['email']},";
        $result.="\n";
        echo $result;
    }
    

    $query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
    $select_c = mysql_query($query) or die(mysql_error()); 
    
    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        echo implode(",", $row)."\n";
    }
    
        14
  •  1
  •   zahid9i    13 年前

    已经很好的解决方案来了。我只是把总代码,让一个新手得到全面的帮助

    <?php
    extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable
    
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=$table.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    require_once("includes/functions.php"); //necessary mysql connection functions here
    
    //first of all I'll get the column name to put title of csv file.
    $query = "SHOW columns FROM $table";
    $headers = mysql_query($query) or die(mysql_error());
    $csv_head = array();
    while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
    {
        $csv_head[] =  $row['Field'];
    }
    echo implode(",", $csv_head)."\n";
    
    //now I'll bring the data.
    $query = "SELECT * FROM $table";
    $select_c = mysql_query($query) or die(mysql_error()); 
    
    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        foreach ($row as $key => $value) {
                //there may be separator (here I have used comma) inside data. So need to put double quote around such data.
            if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
                $row[$key] = '"' . str_replace('"', '""', $value) . '"';
            }
        }
        echo implode(",", $row)."\n";
    }
    
    ?>
    

    <a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>
    

    所以,当我点击链接时,它会下载文件,而不会将我带到浏览器上的csv-download.php页面。

        15
  •  0
  •   Gavin M. Roy    17 年前

    http://us2.php.net/header

    header('Content-type: text/csv');
    header('Content-disposition: attachment; filename="myfile.csv"');
    

    至于制作CSV本身,您只需循环遍历结果集,格式化输出并发送它,就像处理任何其他内容一样。

        16
  •  0
  •   John Hunt    9 年前

    编写自己的CSV代码可能会浪费您的时间,只需使用league/CSV之类的软件包—它可以处理所有困难的事情,文档很好,而且非常稳定/可靠:

    http://csv.thephpleague.com/

    您需要使用composer。如果你不知道作曲家是什么,我强烈建议你看看: https://getcomposer.org/

        17
  •  0
  •   3 revs, 3 users 69%<br/>Vish00722&#13;    7 年前
    <?
        // Connect to database
        $result = mysql_query("select id
        from tablename
        where shid=3");
        list($DBshid) = mysql_fetch_row($result);
    
        /***********************************
        Write date to CSV file
        ***********************************/
    
        $_file = 'show.csv';
        $_fp = @fopen( $_file, 'wb' );
    
        $result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");
    
        while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
        {
            $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
            @fwrite( $_fp, $_csv_data);
        }
        @fclose( $_fp );
    ?>
    
        18
  •  0
  •   ntzm    7 年前

    如何使用PHP脚本编写CSV文件?实际上我也在寻找这个。这是一项简单的PHP任务。 fputs(handler,content)-这个函数对我来说非常有效。首先,您需要打开需要使用fopen($CSVFileName,wb)写入内容的文件。

    $CSVFileName = “test.csv”;
    $fp = fopen($CSVFileName, ‘wb’);
    
    //Multiple iterations to append the data using function fputs()
    foreach ($csv_post as $temp)
    {
        $line = “”;
        $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
        $line .= “\n”;
        fputs($fp, $line);
    }
    
        19
  •  -1
  •   David G    13 年前

    投入 $output

    header("Content-type: application/download\r\n");
    header("Content-disposition: filename=filename.csv\r\n\r\n");
    header("Content-Transfer-Encoding: ASCII\r\n");
    header("Content-length: ".strlen($output)."\r\n");
    echo $output;
    
    推荐文章