search
HomeBackend DevelopmentPHP TutorialHow to create CSV file using PHP? (code example)

CSV (Comma Separated Values) is one of the most common methods of transferring tabular data between applications; creating code to export data to CSV can be useful in many applications. The following article will show you how to use PHP to create CSV files. I hope it will be helpful to you.

How to create CSV file using PHP? (code example)

The following is a detailed introduction through code examples:

Creating CSV files using static data

If you want to store the data into a csv file, you can use code similar to the following:

<?php
// 创建并打开“demosaved.csv”文件进行写入
$file = fopen(&#39;demosaved.csv&#39;, &#39;w&#39;);
 
// 保存列标题
fputcsv($file, array(&#39;Column 1&#39;, &#39;Column 2&#39;, &#39;Column 3&#39;, &#39;Column 4&#39;, &#39;Column 5&#39;));
 
// 样本数据,这可以从MySQL中获取
$data = array(
array(&#39;Data 11&#39;, &#39;Data 12&#39;, &#39;Data 13&#39;, &#39;Data 14&#39;, &#39;Data 15&#39;),
array(&#39;Data 21&#39;, &#39;Data 22&#39;, &#39;Data 23&#39;, &#39;Data 24&#39;, &#39;Data 25&#39;),
array(&#39;Data 31&#39;, &#39;Data 32&#39;, &#39;Data 33&#39;, &#39;Data 34&#39;, &#39;Data 35&#39;),
array(&#39;Data 41&#39;, &#39;Data 42&#39;, &#39;Data 43&#39;, &#39;Data 44&#39;, &#39;Data 45&#39;),
array(&#39;Data 51&#39;, &#39;Data 52&#39;, &#39;Data 53&#39;, &#39;Data 54&#39;, &#39;Data 55&#39;)
);
 
// 保存每一行数据
foreach ($data as $row)
{
fputcsv($file, $row);
}
 
// 关闭文件
fclose($file);
?>

Code description

Line 3: Open File, named "demosaved.csv", for writing. Make sure the server can write to the location where this file is saved

Line 6: Add column headers. If you don't want any column headers, you can skip this step.

Lines 9-15: Indicates the data to be stored in the file. If you want to get data from mysql, you must use code to connect to the database and get the data, and then replace these lines to

Lines 17-21: Iterate through each row of data and save the data

Line 24: Close the file. After we finish writing all the data to the file, we need to close the file.

Get data from mysql to create and automatically download CSV files

<?php
// 设置输出标头,以便下载文件
header(&#39;Content-type: text/csv&#39;);
header(&#39;Content-Disposition: attachment; filename="demo.csv"&#39;);
 
// 不缓存文件
header(&#39;Pragma: no-cache&#39;);
header(&#39;Expires: 0&#39;);
 
// 创建连接到输出流的文件指针
$file = fopen(&#39;php://output&#39;, &#39;w&#39;);
 
// 打开数据库连接
$link = mysqli_connect(&#39;localhost&#39;, &#39;my_user&#39;, &#39;my_password&#39;, &#39;my_db&#39;);
 
//查询数据库
$query = &#39;SELECT field1, field2, field3, field4, field5 FROM table&#39;;
 
if ($rows = mysqli_query($link, $query))
{
// 保存每一行数据
while ($row = mysqli_fetch_assoc($rows))
{
fputcsv($file, $row);
}
//自由结果集
mysqli_free_result($result);
}
// 关闭连接
mysqli_close($link);
?>

Code Description:

Because we want to download the file, we have to send some headers (lines 3 and 4) to tell the browser to download the file.

Line 3: Tell the browser that the MIME type of the content is text/csv, since we are sending a csv file

Line 4: Send the header "Content-Disposition" with its value is "attachment" and the file name is "demo.csv". This will tell the browser to download a file called "demo.csv" instead of displaying it.

Lines 7 and 8: Tell the browser not to cache the file. This is useful if we send multiple files with the same name, otherwise this is not necessary

Line 11: Represents opening the file pointer to send data

Line 14 ~ Line 30: From mysql Get data

Note:You need to make sure to change the connection parameters and queries of the database. Additionally, this database-related code is just an example. In a real application it might be in a different file and there should also be error handling.

The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to create CSV file using PHP? (code example). 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
Laravel routing parameter delivery and controller method definition: Avoiding common errors and best practicesLaravel routing parameter delivery and controller method definition: Avoiding common errors and best practicesJul 23, 2025 pm 07:27 PM

This tutorial details the correct method of parameter passing in Laravel routing, and corrects common errors in writing parameter placeholders into controller method names. The article provides examples of standardized routing definitions and controller methods, and emphasizes that deletion operations should prioritize the use of HTTPDELETE methods to enhance routing semantics and maintainability.

Guide to matching Laravel routing parameter passing and controller methodGuide to matching Laravel routing parameter passing and controller methodJul 23, 2025 pm 07:24 PM

This article aims to resolve common errors in the Laravel framework where routing parameter passing matches controller methods. We will explain in detail why writing parameters directly to the controller method name in the routing definition will result in an error of "the method does not exist", and provide the correct routing definition syntax to ensure that the controller can correctly receive and process routing parameters. In addition, the article will explore best practices for using HTTPDELETE methods in deletion operations.

How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization modelHow to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization modelJul 23, 2025 pm 07:21 PM

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templatesEfficiently use JSON data to implement cascading drop-down menus in Laravel Blade templatesJul 23, 2025 pm 07:18 PM

This article details how to load a local JSON file in a Laravel application and pass its data to a Blade template. By processing JSON parsing by the controller, the view layer uses Blade's @foreach instruction to traverse the data, thereby realizing dynamically generating drop-down menus. In particular, the article also explores in-depth how to combine JavaScript to implement multi-level linkage drop-down menu functions to provide users with dynamic content display based on selection, and provides practical code examples and precautions for implementing such interactions.

Deep analysis of matching Laravel routing parameter transfer and controller methodDeep analysis of matching Laravel routing parameter transfer and controller methodJul 23, 2025 pm 07:15 PM

This article deeply explores the correct transmission of routing parameters and the matching mechanism of controller methods in the Laravel framework. In response to the common "method does not exist" error caused by writing routing parameters directly to the controller method name, the article elaborates on the correct way to define routing, that is, declare parameters in the URI and receive them as independent parameters in the controller method. At the same time, the article also provides code examples and suggestions on best practices for HTTP methods, aiming to help developers build more robust and RESTful Laravel applications.

PHP integrated AI intelligent image processing PHP image beautification and automatic editingPHP integrated AI intelligent image processing PHP image beautification and automatic editingJul 23, 2025 pm 07:12 PM

PHP integrated AI image processing requires the help of a third-party API or local model, which cannot be directly implemented; 2. Use ready-made services such as Google CloudVision API to quickly realize facial recognition, object detection and other functions. The advantages are fast development and strong functions. The disadvantages are that they need to pay, rely on the network and have data security risks; 3. Deploy local AI models through PHP image library such as Imagick or GD combined with TensorFlowLite or ONNXRuntime. It can be customized, the data is safer, and the cost is low, but the development is difficult and requires AI knowledge; 4. Mixed solutions can combine the advantages of API and local model, such as using API for detection and beautification of local models; 5. Selecting AI image processing API should be comprehensive

Twilio Voice Call Maintenance and Recovery: Meeting Functions and Independent Call Leg Management PracticeTwilio Voice Call Maintenance and Recovery: Meeting Functions and Independent Call Leg Management PracticeJul 23, 2025 pm 07:09 PM

This article discusses in-depth two main strategies for realizing voice call holding (Hold) and recovery (Unhold) on the Twilio platform. First, we introduce the detailed introduction to leveraging the Twilio Conference feature to easily manage call retention by updating the Participant resources, and provide corresponding code examples. Second, for scenarios where more detailed control of independent call legs (CallLeg) is required, how to combine TwiML instructions (such as and/) to handle call reconnection, while highlighting the complexity of this approach. The article aims to provide professional and practical guidance to help developers choose the most suitable implementation solution according to specific needs.

Laravel routing parameter passing: correctly define the controller method and routing bindingLaravel routing parameter passing: correctly define the controller method and routing bindingJul 23, 2025 pm 07:06 PM

This article discusses the correct posture of parameter transfer of controller method in Laravel routing in depth. In response to common errors caused by writing routing parameters directly to the controller method name, the correct routing definition syntax is explained in detail, and the mechanism of Laravel automatic parameter binding is emphasized. At the same time, the article recommends using HTTPDELETE method that is more in line with RESTful specifications to handle deletion operations to improve the maintainability and semantics of the application.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.