3

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?

1
  • separate your code in two different files: HTML and PHP. Commented Oct 27, 2014 at 17:46

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

2 Comments

ok, that does the trick. But why does the html gets written in csv, even if I have closed the file pointer?
My guess is because the script continues to execute after you close the file pointer. So even though the file pointer is closed, more output exists after that, the HTML. So it just gets tagged onto the end of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.