Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Trying to create a csv file from a table using php

Options
  • 29-10-2011 3:18pm
    #1
    Registered Users Posts: 53 ✭✭


    Hi there,

    I am trying to allow users download a csv file from my website. This is as far as I have got with the code but it just opens a blank page and doesn't download anything.


    Any advice?
    [PHP]

    <?php
    require_once (MYSQL);
    require_once ('mysqli_connect.php');
    $q="SELECT * FROM table_name";$r = @mysqli_query($dbc, $q);
    $html = "<table>";$html .= "<tr><td>Song</td>";
    $html .= "</tr>";
    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    $html .= "<tr><td>".$row."</td>";
    $html .= "</tr>";}$html .= "</table>";
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment;filename=yourfile.csv");
    echo $html;
    ?>[/PHP]
    Tagged:


Comments

  • Registered Users Posts: 1,657 ✭✭✭komodosp


    Not sure but my first guess might be that a CSV file is a comma delimited file, whereas you seem to be sending a html table...

    In any case, in PHP a blank page often means a syntax error or something if the error reporting is turned off. Have you tried putting this code at the top of your program:
    display_errors(1);
    error_reporting(E_ALL);
    

    Actually I have just noticed that before you open your <?php there's a blank line and then a space - is this in your program too or did it just happen when copying and pasting? - this would cause an error as your headers have already been sent by the time you get to
    header("Content-Type: text/csv");
    
    - If you're going to use the header() function, <?php must be the very first thing in your program, and no output sent before you use header()..


  • Registered Users Posts: 339 ✭✭duffman85


    you're telling the browser that a text file is coming but sending html

    would you not be better creating a file on the server and storing the results of the query in it. then send the file to the browser.

    have a look at the functions here: http://www.php.net/manual/en/book.filesystem.php


  • Registered Users Posts: 53 ✭✭Jemm


    Thanks for the replies but I've managed to fix it in the meantime


  • Registered Users Posts: 6,494 ✭✭✭daymobrew


    For the benefit of others can you post here to describe how you fixed it.


Advertisement