Question

I don't have a lot of experience with using the fputcsv function. I'm trying to make a function, by which an admin can download a file with all the user information.

The CSV should be generated in this way :

Serial Number   Username     Email    etc etc

And then the records from a query.

I have this function which I'm using to generate the csv file :

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // rewrind the "file" with the csv lines
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachement; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

And then I call the function:

<?php
include 'inc/inc.functions.php';
include 'dbconnector.php';
$query="SELECT * from users order by email LIMIT 0,30";
$result=mysql_query($query,$db) or die(mysql_error($db));
$array=mysql_fetch_array($result);

foreach($array as $arr)
{
array_to_csv_download($arr,"records.csv",":");
}

?>

The CSV generated displays: Warning, Invalid argument supplied for foreach.

What should I do to display in the way I require?

UPDATE

http://i.imgur.com/2xH0gT1.png

Was it helpful?

Solution

You're currently calling your function for a single row in the database, rather than for the entire result set. The following should use your function correctly:

$query = "SELECT * from users order by email LIMIT 0,30";
$result = mysql_query($query,$db) or die(mysql_error($db));
$array = array();

# Headers
$array[] = array("Serial Number","Username","Email","etc etc");

while($row = mysql_fetch_row($result)) {
    $array[] = $row;
}
array_to_csv_download($array,"records.csv",":");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top