3

我正在尝试使用CodeIgniter将仅包含两个字段id的简单表导出email到 CSV 文件。csv_from_result()

生成的 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;
4

3 回答 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 修剪掉,因此删除了第一行。

于 2013-04-02T10:23:40.567 回答
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

于 2013-04-02T10:23:34.837 回答
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;
于 2019-01-13T21:28:06.127 回答