Create CSV file with php

How to create csv file with php? Generating csv file with php and download it.

In this article we will discuss about how to create CSV file with php. Rather than creating csv file we will also download the same. This is achieved by the help of fputcsv() function. It formats a line as csv and also writes to an open file.

If you are looking for export excel in codeigniter click here.

PHP

<?php
     $con = mysqli_connect("localhost","root","","registration");
     header('Content-Type: text/csv; charset=utf-8');  
     header('Content-Disposition: attachment; filename=filename.csv');  
     $output = fopen("php://output", "w");  
     fputcsv($output, array('id', 'name', 'age'));  

     $sql = "select * from employees";
     $result = mysqli_query($con,$sql);
     while($row = $result->fetch_assoc())
     {
	 fputcsv($output, $res); 
     } 
     fclose($output);
?>
  1. Connect with database
  2. Send header content type as text/csv with attachment filename.csv
  3. Open file with write permission
  4. Pass the $output and array() values to file to set the header elements
  5. Get data from table
  6. Inside while loop pass the output and each row to fputcsv()
  7. Close the file

Related Posts

forest fire

Forest Fire – Techgig, All testcases passed. Challenge #1

Forest FireĀ (100 Marks) Challenge 1: Forest fire You are camping in a forest area at night. You are living with the forest officers to experience their challenges…

the magic wand

The Magic Wand – TechGig PHP answer, all test cases passed. Challenge #2

The Magic Wand – TechGig PHP answer – all testcases passed The Magic Wand (100 Marks) You are a wizard who possesses the magic wand that can be…

PHP interview Questions and Answers

What is PHP? Answer: PHP stands for Hypertext Preprocessor. It is a widely used server-side scripting language primarily designed for web development. PHP code is embedded within…

install php

A Step-by-Step Guide on How to Install PHP

Install PHP : A Step-by-Step Guide on How to Install PHP Introduction: PHP is a widely used server-side scripting language that powers countless websites and web applications….

what is php

What is PHP? Understanding PHP: The Powerhouse of Web Development

Introduction: What is PHP? Understanding PHP: The Powerhouse of Web Development: In the world of web development, PHP stands tall as one of the most widely-used and…

php form

Complete Php form example

Here we are going to check how to create a php form and insert its values to database table. In this example we will be submitting the…

Leave a Reply

Your email address will not be published. Required fields are marked *