Question

I'm trying to create a csv file direct from a mysql table using php with an OOP approach. Here is my code:

$mysqli = new mysqli($host, $user, $pass, $database);

// Checking connection.
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = 'SELECT * FROM table';
$result = $mysqli->query($query);

while ($row = $result->fetch_array()) {
    $rows[] = $row;
}

    $array = "";
foreach($rows as $row) {
    $array .= "\"".$row["genus"].",".$row["species"]."\",";
}

$list = array($array);

header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=export.csv');

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

foreach ($list as $line) {
    fputcsv($file,explode(',',$line));
}

fclose($file);
// Free result set.
$result->close();

// Close connection.
$mysqli->close();

My problem is with the following part, when creating the array:

    $array = "";
foreach($rows as $row) {
    $array .= "\"".$row["genus"].",".$row["species"]."\",";
}

because when I do a print_r ($list); I don't receive the expected array: Array ( [0] => "homo,sapiens", [1] => "homo,erectus", [2] => "homo,ergaster", )

but this one: Array ( [0] => "homo,sapiens","homo,erectus","homo,ergaster", )

and moreover when I create the array manually

$list = array("homo,sapiens","homo,erectus","homo,ergaster");

it works just fine and I receive the correct csv file.

I would appreciate if someone could help me, explain me what I'm doing wrong and what I should do to fix the code.

Was it helpful?

Solution

That's because you're treating $array as a string, not an array. This should work:

$array = array();
foreach($rows as $row) {
    $array[] = "\"".$row["genus"].",".$row["species"]."\",";
}

I think you're expecting the $list = array($array); line to magically convert a comma separated string to individual elements in the array, but it doesn't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top