CSV file from MySQL using PHP with a OOP aproach (mysqli->connect, etc.)

落爺英雄遲暮 提交于 2019-12-25 04:29:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23642362/csv-file-from-mysql-using-php-with-a-oop-aproach-mysqli-connect-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!