All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

Create CSV File Using PHP And Save It Into Directory

Last Updated : Mar 11, 2024

Create CSV File Using PHP And Save It Into Directory

In this article we will show you the solution of create csv file using PHP and save it into directory, the CSV (comma-separated values) file format is most commonly used to store plain text data.

This is because it allows for storing both comma-separated values and plain text data.

A CSV file format is the best choice when it comes to importing and exporting data in the web application.

The fopen() function can be used to save a CSV file to a directory with the right choice of parameters. Specifically, we will use the parameter a which instructs PHP to open a new file, create it if it doesn't already exist, and write to it.

An array can be converted into a CSV file with fputcsv(). A line can be formatted as a CSV (comma-separated values) file using the fputcsv() function.

A successful call to fputcsv() will return the length of the written string, while a failure will return FALSE.

Step By Step Guide On Create Csv File Using PHP And Save It Into Directory :-

$list = array (
    ['Name', 'age', 'Gender'],
    ['murfi', 10, 'Male'],
    ['thomas', 25, 'Male'],
    ['Jessy', 30, 'Female']
// Open a file in write mode ('w')
$fp = fopen ('persons.csv', 'w');
// Loop through file pointer and a line
foreach ($list as $fields) {
    fputcsv ($fp, $fields);
  1. The short tags start with "<?" and end with "?>".
  2. It consists of values, variables, or references identified by one or more identifiers (e.g., values, variables or references).
  3. When the filename is passed to the fopen () function, the filename is converted into a filename. It specifies the type of access requested by the mode parameter
  4. When a false condition is met, the loop is iterated through using the foreach tag.
  5. A line is then formatted as CSV and written to an open file using the fputcsv () function.
  6. The fclose () function closes an open file pointer.

Conclusion :-

Following the execution of the PHP program, a persons.csv file

PHP can be used to implement import and export features in web applications easily.

CSV File Data Import into MySQL database using PHP was discussed in our previous tutorial.

I hope this article on create csv file using PHP and save it into directory helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Ashish

Ashish is a dynamic and motivated individual with a passion of programming and an experienced programmer having 3+ years of experience in various languages like Java, Python, HTML, CSS, JavaScript, jQuery and various frameworks like Bootstrap

Follow Ashish On Linkedin 🡪