📘 Lesson  ·  Lesson 44

Export to CSV/Excel

Export to CSV/Excel

About

This script exports database rows into a CSV file that opens in Excel — useful for reports and downloads.

Export Script

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

$out = fopen("php://output", "w");
fputcsv($out, ["ID", "Name", "Marks"]);   // header row

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

Summary

  • Set CSV headers, then write rows with fputcsv() to php://output.
  • The browser downloads it as a file that opens in Excel.

परिचय

यह script database rows को CSV file में export करता है जो Excel में खुलती है — reports और downloads के लिए उपयोगी।

Export Script

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

$out = fopen("php://output", "w");
fputcsv($out, ["ID", "Name", "Marks"]);   // header row

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

सारांश

  • CSV headers set करें, फिर fputcsv() से rows php://output में लिखें।
  • Browser इसे Excel में खुलने वाली file के रूप में download करता है।
← Back to PHP Tutorial
🔗

Share this topic with a friend

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

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

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