Showing posts with label PHP CSV. Show all posts
Showing posts with label PHP CSV. Show all posts

Friday, 2 August 2019

PHP function used to read CSV files

The below function can be used to read CSV files and returning an array with all values obtained from the CSV file
USAGE:
Copy the below function to your PHP script
function readCSV($csvFile){
 
 
        $file_handle = fopen($csvFile, 'r');
 
        while (!feof($file_handle) ) {
 
                $line_of_text[] = fgetcsv($file_handle, 1024);
 
        }

How to force a CSV file to download when clicking on a download link using PHP

Example: We have a CSV file called example.csv we want users to download to use as a template. Now some browsers will display the contents of the file instead of asking users to download the file. What we want to do is to force the downloadinstead of displaying the contents in the browser.
  • Create a new PHP file called ‘download.php
  • Open the file for editing
  • Copy the code below into the ‘download.php‘ file
    {codecitation style=”brush: PHP;”}
    header(‘Content-Type: application/csv’); //Outputting the file as a csv file
    header(‘Content-Disposition: attachment; filename=example.csv’); //Defining the name of the file and suggesting the browser to offer a ‘Save to disk ‘ option
    header(‘Pragma: no-cache’);
    echo readfile(‘example.csv’); //Reading the contents of the file
    {/codecitation}
  • Now on the page where you want the user to click on the link to download the file add the following code
    {codecitation style=”brush: HTML;”}
    <a href=”/download.php”>Click here to download an example of the “CSV” file</a>
    {/codecitation}
  • Now everytime the user clicks on the link the browser won’t display the contents but will offer to download the file

Tuesday, 25 September 2018

Write data into CSV file using PHP

Sometimes we need to generate CSV file containing data from database table. So, in this tutorial, we are going to learn how to write data into CSV file using PHP. PHP has a default function fputcsv(), through which we can write data into CSV file. In this code, we will fetch data from MySQL table and generate a CSV file.

Database – Write data into CSV file

  1. CREATE TABLE IF NOT EXISTS `user_details` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(50) NOT NULL,
  4. `mobile` bigint(10) NOT NULL,
  5. `country` varchar(50) NOT NULL,
  6. PRIMARY KEY (`id`)
  7. );
  8. INSERT INTO `user_details` (`id`, `name`, `mobile`, `country`) VALUES
  9. (1, 'Aritra Samanta', 9999999991, 'India'),
  10. (2, 'Rina Saha', 9999999992, 'Australia'),
  11. (3, 'Anil Das', 9999999993, 'London'),
  12. (4, 'Akash Samanta', 9999999994, 'America'),
  13. (5, 'Niharika Roy', 9999999995, 'Bulgeria');
Create the above table into the database and insert the example data into that table.
  1. <?php
  2. define('HOSTNAME','localhost');
  3. define('DB_USERNAME','database_username');
  4. define('DB_PASSWORD','database_password');
  5. define('DB_NAME', 'database_name');
  6. $con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
  7. //Check connection
  8. if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
  9. ?>
Create a PHP file “db.php” in the root folder and write the above database connection code into it. Change the database credentials as yours.

HTML code – Write data into CSV file

  1. <?php
  2. include("db.php");
  3. $sql = "select * from `user_details`";
  4. $res = mysqli_query($con, $sql);
  5. if(mysqli_num_rows($res) > 0) {
  6. ?>
  7. <form action="csv.php" method="post">
  8. <input type="submit" name="submitBtn" id="submitBtn" value="Generate CSV" />
  9. <table id="100%" cellpadding="5" cellspacing="1">
  10. <tbody>
  11. <tr>
  12. <th>SL.</th>
  13. <th>NAME</th>
  14. <th>MOBILE</th>
  15. <th>COUNTRY</th>
  16. </tr>
  17. <?php
  18. while($row = mysqli_fetch_array($res)) {
  19. ?>
  20. <tr>
  21. <td align="center"><?php echo $row['id']; ?>.</td>
  22. <td><?php echo $row['name']; ?></td>
  23. <td align="center"><?php echo $row['mobile']; ?></td>
  24. <td><?php echo $row['country']; ?></td>
  25. </tr>
  26. <?php
  27. }
  28. ?>
  29. </tbody>
  30. </table>
  31. </form>
  32. <?php
  33. }
  34. ?>
Create a PHP file “index.php” in the root folder and write the above contents in it. This page simply displays the contents of the table in a tabular form and a submit button which generates a CSV file based on the table data.

PHP code – Write data into CSV file

  1. <?php
  2. include("db.php");
  3. if(isset($_POST['submitBtn'])) {
  4. $filename = date('d-m-Y_H-i-s').".csv";
  5. $file = fopen("php://output","w");
  6. header('Content-type: application/csv');
  7. header('Content-Disposition: attachment; filename='.$filename);
  8. //Here we fetch the column names of the table and write these into the CSV file
  9. $query = "select column_name from information_schema.columns where table_schema='database_name' and table_name='user_details'"
  10. $result = mysqli_query($con, $query);
  11. while ($row = mysqli_fetch_row($result)) {
  12. $column_header[] = $row[0];
  13. }
  14. fputcsv($file, $column_header);
  15. //Here we fetch the data from the table and write these data into the CSV file row wise.
  16. $sql = "select * from `user_details`";
  17. $res = mysqli_query($con, $sql);
  18. if(mysqli_num_rows($res) > 0) {
  19. while($row = mysqli_fetch_assoc($res)) {
  20. fputcsv($file, $row);
  21. }
  22. }
  23. }
  24. ?>
Create another PHP file “csv.php” in the root folder and write the above contents in it.
  1. $filename = date('d-m-Y_H-i-s').".csv";
  2. $file = fopen("php://output","w");
  3. header('Content-type: application/csv');
  4. header('Content-Disposition: attachment; filename='.$filename);
The filename is dynamic, a combination of date and time. The second, third and fourth line forced to download the file as a CSV file instead of open the page in the browser.
  1. $query = "select column_name from information_schema.columns where table_schema='database_name' and table_name='user_details'";
  2. $result = mysqli_query($con, $query);
  3. while ($row = mysqli_fetch_row($result)) {
  4. $column_header[] = $row[0];
  5. }
  6. fputcsv($file, $column_header);
The above code performs a simple query and fetches the column names of the table and stores in an array variable “$column_header“. fputcsv($file, $column_header) writes the column names in the CSV file as the first row.
  1. $sql = "select * from `user_details`";
  2. $res = mysqli_query($con, $sql);
  3. if(mysqli_num_rows($res) > 0) {
  4. while($row = mysqli_fetch_assoc($res)) {
  5. fputcsv($file, $row);
  6. }
  7. }
Fetch all data from the table and writes them one by one into the CSV file.
Download the full source code from the below download link and please like and share this tutorial link to others.