我正在尝试使用以下代码将列表页面导出到csv文件。
public function export()
{
$customers = \CI::Customers()->get_customer_export();
\CI::load()->helper('download_helper');
force_download('customers.csv', ($customers));
}
它生成并错误第二个参数应该是一个字符串而不是任何数组。如果我尝试json_encode $ customers变量,它会创建一个文件,但在csv文件中输出json代码。
感谢任何帮助
答案 0 :(得分:1)
尝试使用此功能:首先,您已将此代码放在帮助程序中:
function array_to_csv($array, $download = "")
{
if ($download != "")
{
header('Content-Description: File Transfer');
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachement; filename="' . $download . '"');
header('Content-Transfer-Encoding: binary');
}
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$n = 0;
foreach ($array as $line)
{
$n++;
if ( ! fputcsv($f, $line))
{
show_error("Can't write line $n: $line");
}
}
fclose($f) or show_error("Can't close php://output");
$str = ob_get_contents();
ob_end_clean();
if ($download == "")
{
return $str;
}
else
{
print "\xEF\xBB\xBF"; // UTF-8 BOM
print $str;
}
}
阵列形成应该是:
Array
(
[0] => Array
(
[0] => 1
[1] => 0
[2] => Test 1
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => Test 1.1
)
[2] => Array
(
[0] => 3
[1] => 1
[2] => Test 1.2
)
)
答案 1 :(得分:0)
为简单起见,您还可以使用“CI数据库实用程序类”,如下所示:
public class BookResource extends Resource<Book> {
public BookResource(Book content, Link... links) {
super(content, links);
}
}
查看下面的用户指南,了解更多信息https://www.codeigniter.com/userguide3/database/utilities.html