Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 44

Export Data to CSV in PHP

In this lesson: Download MySQL table data as CSV/Excel file in PHP with fputcsv and headers — ready-to-use code. Export in 2 minutes.

What is a CSV export

A CSV export lets users download data — a list of orders, students, sales — as a spreadsheet file. CSV is plain text where each line is a row and commas separate columns. Because Excel and Google Sheets open it directly, it is the standard way to hand data to users.

💡 Two parts: send download headers so the browser saves a file, then write the rows with fputcsv.

Download headers

These headers, sent before any output, tell the browser to download the response as a file.

<?php
  header("Content-Type: text/csv");
  header('Content-Disposition: attachment; filename="data.csv"');
?>

Content-Type says it is CSV; Content-Disposition: attachment forces a download with the given filename. There must be no output (not even a space) before these.

Writing rows with fputcsv

<?php
  header("Content-Type: text/csv");
  header('Content-Disposition: attachment; filename="data.csv"');

  $out = fopen("php://output", "w");
  fputcsv($out, ["Name", "Marks"]);   // header row
  fputcsv($out, ["Aman", 88]);
  fputcsv($out, ["Diya", 92]);
  fclose($out);
?>
Name,Marks
Aman,88
Diya,92

We open php://output (the browser download stream) and write each row with fputcsv, which formats commas and quotes correctly for us.

Exporting from MySQL

<?php
  header("Content-Type: text/csv");
  header('Content-Disposition: attachment; filename="students.csv"');

  $out = fopen("php://output", "w");
  fputcsv($out, ["Name", "Marks"]);   // column titles

  $stmt = $pdo->query("SELECT name, marks FROM students");
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      fputcsv($out, [$row["name"], $row["marks"]]);
  }
  fclose($out);
?>

Write a header row of column names, then loop the database results and write each as a CSV row. The browser downloads a ready-to-open spreadsheet.

Opening in Excel

The downloaded .csv opens directly in Excel or Google Sheets — each comma becomes a column boundary, each line a row. For non-English text, write a UTF-8 BOM first so accents and Hindi display correctly:

<?php
  echo "\xEF\xBB\xBF";  // UTF-8 BOM for Excel
?>

Common mistakes

  • Output before the headers. Any space or echo first causes "headers already sent".
  • Joining values with commas by hand. Use fputcsv so values with commas or quotes are handled.
  • Forgetting the header row. Without column titles the file is hard to read.
  • Wrong encoding for Hindi/accents. Add a UTF-8 BOM so Excel shows them correctly.

Summary

  • CSV is a plain-text spreadsheet format that opens in Excel.
  • Send Content-Type and Content-Disposition headers to force a download.
  • Write rows with fputcsv to php://output.
  • Export from MySQL by looping results and writing each row.
  • Add a UTF-8 BOM for correct Hindi/accented text in Excel.

Next, read the data first with PHP CRUD, or connect safely with PHP MySQL connection.

Frequently Asked Questions

What is a CSV file?
CSV (Comma-Separated Values) is a plain-text spreadsheet format where each line is a row and commas separate the columns. It opens in Excel, Google Sheets and almost every data tool, which makes it the standard way to export data.
How do I make the browser download the CSV?
Send two headers before any output: Content-Type: text/csv and Content-Disposition: attachment; filename="data.csv". These tell the browser to download the response as a file instead of showing it.
What does fputcsv do?
fputcsv takes an array and writes it as one properly formatted CSV row, handling commas and quotes inside values automatically. It is safer than joining values with commas yourself.
How do I export MySQL data to CSV?
Query the rows, write a header row of column names, then loop the results and write each row with fputcsv. Send the download headers first so the browser saves it as a file.
Why is there no output before the headers?
Headers must be sent before any HTML or text, or PHP gives a "headers already sent" error. Make sure there are no spaces or echoes before your header() calls.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicGenerate PDF (FPDF) Your progress: 44 / 50 (88%) · Lesson 45 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free