user6611859 user6611859 - 4 months ago 36
PHP Question

Exporting an empty CSV file PHP

I retrieve data from a database in a table and i want to export it.

This's my code :

<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;
?>


When I click to the button "export at csv" it gives me file named mydata empty.

Help please.

Thanks

Answer

You can do all these in one single File (the same file that contains the Form). The Process is very simple... Within the foreach Loop, you build the contents of the CSV File to be exported and save it into a Variable. Then you set the value of the Hidden Input Field (csv_text) to the Variable. But still, at the top of your Script, you'd check if the Form has been Submitted. If "YES", then just go ahead and simply process the CSV File (Save it and offer it up for Download).

Note that a new input field was added to allow the User to choose a preferred Name for the File.... The code Below illustrates the Procedure:

<?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>

Hope this Helps....

Cheers and Good Luck ;-)