来自MySQL的CSV文件,使用带有OOP方法的PHP(mysqli-> connect等) [英] CSV file from MySQL using PHP with a OOP aproach (mysqli->connect, etc.)

查看:53
本文介绍了来自MySQL的CSV文件,使用带有OOP方法的PHP(mysqli-> connect等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用php和OOP方法直接从mysql表创建一个csv文件.这是我的代码:

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"]."\",";
}

因为当我执行print_r($ list)时;我没有收到预期的数组: 数组([0] =>"homo,sapiens",[1] =>"homo,erectus", [2] =>"homo,ergaster",)

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", )

但是这个: 数组([0] =>"homo,sapiens","homo,erectus","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");

它工作正常,我收到了正确的csv文件.

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.

推荐答案

那是因为您将$array视为字符串,而不是数组. 这应该起作用:

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"]."\",";
}

我认为您期望$list = array($array);行能够将逗号分隔的字符串神奇地转换为数组中的各个元素,但事实并非如此.

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.

这篇关于来自MySQL的CSV文件,使用带有OOP方法的PHP(mysqli-> connect等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆