在CodeIgniter中的csv_from_result()函数中如何跳过第一行?

3

我正在尝试使用CodeIgniter中的csv_from_result()将一个只包含两个字段idemail的简单表格导出到CSV文件。

生成的CSV文件的第一行包含列名,但我只想要数据。

是否有方法可以跳过这个第一行?

这是我的代码:

$query = $this->EE->db->query("SELECT email FROM exp_sct_mailing_list");

$this->EE->load->dbutil();
$data = $this->EE->dbutil->csv_from_result( $query, ",", "\r\n" );

$this->EE->load->helper('download');
force_download("mailing_list.csv", $data);
exit;

顺便说一下,我在ExpressionEngine中使用CodeIgniter。 - laurent
3个回答

4
最简单的方法是删除第一行,就像这样:
$query = $this->EE->db->query("SELECT email FROM exp_sct_mailing_list");

$this->EE->load->dbutil();
$data = ltrim(strstr($this->EE->dbutil->csv_from_result($query, ',', "\r\n"), "\r\n"));

$this->EE->load->helper('download');
force_download("mailing_list.csv", $data);
exit;

在这里,我们仅提取第一个CRLF \r\n之后的内容,直到数据的末尾。然后,我们将左侧的CRLF修剪掉,因此已删除了第一行。


我不明白你如何使用csv_from_result。你能展示一下如何将其应用到我上面粘贴的代码中吗? - laurent

1

遗憾的是,无法向函数csv_from_result传递参数并避免列名,但是您可以根据原始函数的代码构建自定义csv_from_result函数并删除不需要的部分:

/**
* Generate CSV from a query result object
*
* @param object $query Query result object
* @param string $delim Delimiter (default: ,)
* @param string $newline Newline character (default: \n)
* @param string $enclosure Enclosure (default: ")
* @return string
*/
function my_custom_csv_from_result($query, $delim = ',', $newline = "\n", $enclosure = '"')
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('You must submit a valid result object');
}

$out = '';

// Blast through the result array and build out the rows
while ($row = $query->unbuffered_row('array'))
{
foreach ($row as $item)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
}
$out = substr(rtrim($out), 0, -strlen($delim)).$newline;
}

return $out;
}

该代码基于从这里获取的csv_from_result实现:https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_utility.php

我知道这可能是最干净的方法,但重写CodeIgniter对我来说太难了!感谢您的时间。 - laurent
谢谢分享,我已经成功将它合并到我的代码中。对于那些感兴趣的人,我在我的模型中处理CSV的头部,该模型返回一个通用数组,然后我通过修改后的csv_from_result方法在控制器中循环遍历它。如果有人需要示例,我可以发布它。 - spyke01

0

你可以使用array_shift

$data = array_values(array_shift($data)); 

这将删除第一行。

你的代码将变为:

$query = $this->EE->db->query("SELECT email FROM exp_sct_mailing_list");

$this->EE->load->dbutil();
$data = $this->EE->dbutil->csv_from_result( $query, ",", "\r\n" );

$data = array_values(array_shift($data)); //skip the first line

$this->EE->load->helper('download');
force_download("mailing_list.csv", $data);
exit;

无法工作,显示错误“array_shift()期望参数1为数组,但提供了字符串”。 - Abed Putra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接