Create CSV File Using PHP And Save It Into Directory
Last Updated : Mar 11, 2024
IN - PHP | Written & Updated By - Ashish
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 :-
<?php $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); } fclose($fp); ?>
- The short tags start with "<?" and end with "?>".
- It consists of values, variables, or references identified by one or more identifiers (e.g., values, variables or references).
- 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
- When a false condition is met, the loop is iterated through using the foreach tag.
- A line is then formatted as CSV and written to an open file using the fputcsv () function.
- 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.