Home  >  Article  >  Backend Development  >  How to create CSV file in PHP

How to create CSV file in PHP

WBOY
WBOYOriginal
2023-06-11 14:51:072344browse

CSV (Comma-Separated Values) file format is widely used for data exchange and import/export jobs. In PHP, CSV files can be easily created using the built-in file manipulation functions and CSV functions. In this article, we will learn how to create CSV files using PHP.

Step 1: Create a CSV file

To create a CSV file, you first need to open a file handle and set the open mode of the file. In this example, we open the file in write mode, and if the file does not exist, it will create a new file:

$file = fopen('sample.csv', 'w');

Step 2: Write CSV header information

Next , you need to write the header information of the CSV file to the file. It should include the column names that are the information you want to store in the CSV file. We can use the fputcsv() function to write the header data to the CSV file:

$header = array('Name', 'Email', 'Phone');
fputcsv($file, $header);

Step 3: Write CSV data

Next, we need to write each row of data to the file. In a CSV file, each row should correspond to a column of header information. To explain this process, we will assume that we have the following data to write to a CSV file:

$data = array(
    array('John Doe', 'johndoe@email.com', '123-456-7890'),
    array('Jane Doe', 'janedoe@email.com', '987-654-3210'),
    array('Bob Smith', 'bobsmith@email.com', '555-555-5555')
);

We can then use a loop to write each row of data into the CSV file:

foreach ($data as $row) {
    fputcsv($file, $row);
}

Step 4: Close the file handle

After we finish writing the CSV data, we need to close the CSV file. Once the file is closed, we have completed the creation of the CSV file.

fclose($file);

Here is the complete code snippet:

$file = fopen('sample.csv', 'w');

$header = array('Name', 'Email', 'Phone');
fputcsv($file, $header);

$data = array(
    array('John Doe', 'johndoe@email.com', '123-456-7890'),
    array('Jane Doe', 'janedoe@email.com', '987-654-3210'),
    array('Bob Smith', 'bobsmith@email.com', '555-555-5555')
);

foreach ($data as $row) {
    fputcsv($file, $row);
}

fclose($file);

Summary

In this article, we learned how to create a CSV file using PHP. Using the steps above, you can easily save your data in CSV format and import it into other applications or databases when needed. Proficiency in the creation of CSV files provides more options for data exchange and conversion.

The above is the detailed content of How to create CSV file in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn