Sourabh
Sourabh

Reputation: 765

export mysql table data to csv file through php..html also get dumped

So I was trying to export mysql table to csv file via php. This is the code

<?php if (isset($_POST['exp'])) {

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

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

    fputcsv($output, array('User ID', 'User Name', 'Password'));
    $con = mysqli_connect('localhost', 'root', 'pass', 'xyz');
    $rows = mysqli_query($con, 'SELECT * FROM users');

    while ($row = mysqli_fetch_assoc($rows)) {
      fputcsv($output, $row);
    }
    fclose($output);
    mysqli_close($con);
  }
?>

<div>
  <form action="#" method="post">
    <input type="submit" value="Export" name="exp" />
  </form>
</div>

Every thing is fine but the html part also gets dumped in the csv file. here is screen shot of the csv csv output

Why is that happening? Am I doing anything wrong?

Upvotes: 3

Views: 7105

Answers (1)

slapyo
slapyo

Reputation: 2991

Your page continues to load beyond the PHP. Add exit() at the end inside the IF statement and it will stop running right there.

<?php if (isset($_POST['exp'])) {

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

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

    fputcsv($output, array('User ID', 'User Name', 'Password'));
    $con = mysqli_connect('localhost', 'root', 'pass', 'xyz');
    $rows = mysqli_query($con, 'SELECT * FROM users');

    while ($row = mysqli_fetch_assoc($rows)) {
      fputcsv($output, $row);
    }
    fclose($output);
    mysqli_close($con);
    exit();
  }
?>

<div>
  <form action="#" method="post">
    <input type="submit" value="Export" name="exp" />
  </form>
</div>

Upvotes: 4

Related Questions