Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Trying to create a csv file from a table using php

  • 29-10-2011 03:18PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 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, Registered Users 2 Posts: 53 ✭✭Jemm


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


  • Registered Users, Registered Users 2 Posts: 6,652 ✭✭✭daymobrew


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


Advertisement