1

Hi i'm trying to export the data from mysql db to csv file by making it downloadable in .csv form.

Here is my code :

<?php 
if(isset($_GET['Download']))
{
include 'conn.php';

$stmt = $pdo->prepare("select * from table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$filename = "export.csv";

$f = fopen('php://output', 'w'); 

header('Content-Type: text/csv');

header('Content-Disposition: attachement; filename="export.csv"');

header("Pragma: no-cache");

header("Expires: 0");

foreach ($rows as $line) { 
    fputcsv($f, $line); 
}


fclose($f);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<form class="form-horizontal" action="<?php echo $_SERVER["PHP_SELF"];?>" method="GET" >
<input type="submit" name="Download" value="Download" class="submit" />

</script>
</form>
</body>
</html>

Now, the browser asks the user to save the file as. and the file is also being downloaded but the download never completes and the csv file contains the data as well as the code. Which i dont want. It seems there is some error in the header. Please help.

2
  • die(); after your PHP code Commented Aug 27, 2014 at 7:54
  • 1
    Why don't you try some GUI tool like Navicat (Native Application) or phpMyAdmin (Web Application)? Commented Aug 27, 2014 at 7:56

1 Answer 1

2

Try putting an exit(); directly after fclose($f); -- otherwise it will include the HTML in the download as well.

Sign up to request clarification or add additional context in comments.

1 Comment

It helped me exclude the html part but still the download isnt completed. Why is that happening?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.