导出一个空的CSV文件PHP

时间:2016-07-20 05:43:30

标签: php csv

我从表中的数据库中检索数据,我想将其导出。

这是我的代码:

<form action="/csv_file/getCSV.php" method="POST">
<input type="hidden" name="csv_text" id="csv_text"> 
<input type="submit" value="Export as CSV" onclick="getCSVData()" class="btn btn-success">

      <table id="table_with_sorting" style="zoom: 85%">
         <thead>
           <tr>
              <th>Name</th>
              <th>Code</th>
              <th>Supplier</th>
          </tr>
        </thead>
         <?php
            foreach ( $data as $q => $v ) :
        ?>
        <td><? echo $v['name']; ?></td>
        <td><? echo $v['code']; ?></td>
        <td><? echo $v['supplier']; ?></td>

        <?php
         endforeach;
        ?>
        </table>

Page getCSV.php:

<?php

  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"my-data.csv\"");
  $data=stripcslashes($_REQUEST['csv_text']);
  echo $data; 
?>

当我点击按钮&#34;导出csv&#34;它给我一个名为mydata的文件为空。

请帮助。

由于

1 个答案:

答案 0 :(得分:0)

您可以在一个文件(包含表单的同一文件)中执行所有这些操作。过程非常简单...在foreach循环中,您构建要导出的CSV文件的内容并将其保存到Variable。然后将隐藏输入字段(csv_text)的值设置为变量。但是,在脚本的顶部,您还要检查表单是否已提交。如果“是”,则只需继续处理CSV文件(保存并提供下载)。

请注意,添加了一个新的输入字段,以允许用户为文件选择首选名称....下面的代码说明了过程:

<?php  // WARNING! NOTICE THERE IS NO SPACE BEFORE <?php

        // CREATE A VARIABLE TO HOLD THE VALUE TO BE PASSED TO THE HIDDEN FIELD:
        // THIS VARIABLE HOLDS THE CONTENTS OF THE CSV DATA WE WANT TO EXPORT...
        $csvData    = "";

        // WE DON'T HAVE ACCESS TO YOUR DATABASE SO WE SIMULATE AN ARRAY
        // OF ROWS CONTAINING SOME DATA  (JUST FOR TESTING PURPOSES)
        // HOWEVER, WITH THE DATA FROM YOUR DB, THE CODE WOULD STILL FUNCTION. 
        $data       = array(
                        array("name"=>"Landry", "code"=>"123", "supplier"=>"ABC"),
                        array("name"=>"James",  "code"=>"456", "supplier"=>"DEF"),
                        array("name"=>"Paul",   "code"=>"789", "supplier"=>"GHI"),
                        array("name"=>"Nathan", "code"=>"012", "supplier"=>"JKL"),
                    );


        /**
         * 
         * FUNCTION THAT PROMPTS USER TO DOWNLOAD THE EXPORTED CSV FILE
         * @param $downloadFileName // FULL-NAME OF THE FILE TO DOWNLOAD     
         * @param null $newFileName // NEW-NAME FOR THE FILE... DO NOT USE EXTENSIONS LIKE .csv
         * @return bool
         *
         */
        function processDownload($downloadFileName, $newFileName=null) {
            $ext            = pathinfo($downloadFileName, PATHINFO_EXTENSION);
            if(!$newFileName){
                $newFileName  = basename($downloadFileName);
            }else{
                $newFileName .= "." . $ext;
            }
            if(file_exists($downloadFileName)){
                $size       = @filesize($downloadFileName);
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . $newFileName );
                header('Content-Transfer-Encoding: binary');
                header('Connection: Keep-Alive');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . $size);
                readfile($downloadFileName);
                return TRUE;
            }
            return FALSE;
        }

        // CHECK IF THE SUBMIT BUTTON WAS CLICKED
        if( isset($_POST['submit']) ){
            $csvTextData    = $_POST['csv_text'];       // GET CSV DATA (INCLUDING HEADER)
            $csvFileName    = $_POST['csv_file_name'];  // GET THE USER-DEFINED FILE-NAME
            $fileName       = "my-data.csv";            // CREATE A DEFAULT FILE NAME

            if($csvTextData && !empty($csvTextData)){
                if($csvFileName){
                    $fileName = stristr($csvFileName,".csv")? $fileName : $fileName . ".csv";
                }
                // SAVE THE CSV FILE TO YOUR SYSTEM...
                file_put_contents($fileName, $csvTextData);

                // LAUNCH THE DOWNLOAD
                processDownload($fileName, $csvFileName);
            }
        }

    ?>

    <form action="" method="POST">
        <!-- GIVE THE USER A CHANCE TO CHOOSE HIS FILE-NAME -->
        <input type="text" value=""  name="csv_file_name" class="" placeholder="Enter desired File-Name"><br />
        <input type="submit" value="Export as CSV" name="submit" class="btn btn-success">

        <table id="table_with_sorting" style="zoom: 85%">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Code</th>
                    <th>Supplier</th>

                    <!-- BUILT THE CSV FILE HEADER AND STORE IT IN THE $csvData VARIABLE-->
                    <?php $csvData .= "Name,\tCode,\tSupplier\n"?>
                </tr>
            </thead>
            <?php
                foreach ( $data as $q => $v ) :
                    // BUILD THE CSV VALUE-DATA AND ADD IT TO THE $csvData VARIABLE
                    // ON EACH ITERATION THROUGH THE FOREACH LOOP.
                    $csvData .= $v['name'] . ",\t" . $v['code'] . ",\t" . $v['supplier'] . "\n";
                    ?>
                    <tr>
                        <td><? echo $v['name']; ?></td>
                        <td><? echo $v['code']; ?></td>
                        <td><? echo $v['supplier']; ?></td>
                    </tr>

                    <?php
                endforeach;
            ?>
            <input type="hidden" name="csv_text" id="csv_text" value="<?php echo $csvData; ?>">
        </table>

希望这有助于......

干杯和好运; - )