【发布时间】:2011-07-16 19:04:06
【问题描述】:
我正在尝试将一些 MYSQL 查询转换为 MYSQLI,但我遇到了问题,下面是我遇到问题的脚本的一部分,该脚本将查询转换为 csv:
$columns = (($___mysqli_tmp = mysqli_num_fields($result)) ? $___mysqli_tmp : false);
// Build a header row using the mysql field names
$rowe = mysqli_fetch_assoc($result);
$acolumns = array_keys($rowe);
$csvstring = '"=""' . implode('""","=""', $acolumns) . '"""';
$header_row = $csvstring;
// Below was used for MySQL, Above was added for MySQLi
//$header_row = '';
//for ($i = 0; $i < $columns; $i++) {
// $column_title = $file["csv_contain"] . stripslashes(mysql_field_name($result, $i)) . $file["csv_contain"];
// $column_title .= ($i < $columns-1) ? $file["csv_separate"] : '';
// $header_row .= $column_title;
// }
$csv_file .= $header_row . $file["csv_end_row"]; // add header row to CSV file
// Build the data rows by walking through the results array one row at a time
$data_rows = '';
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $columns; $i++) {
// clean up the data; strip slashes; replace double quotes with two single quotes
$data_rows .= $file["csv_contain"] .$file["csv_equ"] .$file["csv_contain"] .$file["csv_contain"] . preg_replace('/'.$file["csv_contain"].'/', $file["csv_contain"].$file["csv_contain"], stripslashes($row[$i])) . $file["csv_contain"] .$file["csv_contain"] .$file["csv_contain"];
$data_rows .= ($i < $columns-1) ? $file["csv_separate"] : '';
}
$data_rows .= $this->csv_end_row; // add data row to CSV file
}
$csv_file .= $data_rows; // add the data rows to CSV file
if ($this->debugFlag) {
echo "Step 4 (repeats for each attachment): CSV file built. \n\n";
}
// Return the completed file
return $csv_file;
我遇到的问题是在为列标题构建标题行时 mysqli 不使用 field_names 所以我通过使用mysqli_fetch_assoc() 然后implode() 数组来获取列标题,添加,' s 等用于 csv。
这可行,但是当我生成 csv 时,我会在标题处于活动状态时删除第一个数据行,当我删除脚本的标题部分并将标题保留为空时,我会得到所有数据行和一个空白标题(如预期)。
所以在将我的标头加入数组到$csv_file 时,我一定遗漏了一些东西。
谁能指出我正确的方向?
非常感谢
本
【问题讨论】:
-
有什么理由不能使用
fputcsv? -
只是因为我使用的代码自动通过电子邮件发送 csv 文件,我认为更改此代码比重新开始更容易
-
编写自己的 CSV 格式化程序很容易出错,duplicates existing functionality。如果您需要字符串中的数据,您仍然可以通过写入
php://temp流(使用stream_get_contents将结果保存到流中)或string stream 来使用fgetcsv。