laurent
laurent

Reputation: 515

Skip First Line In csv_from_result() In CodeIgniter

I'm trying to export a simple table containing only two fields id, email to a CSV file using csv_from_result() in CodeIgniter.

The first line of the generated CSV file contains the name of the column, but I only want the the data.

Is there any way to skip this fist line?

This is my code :

$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;

Upvotes: 3

Views: 5451

Answers (3)

user2858034
user2858034

Reputation: 1

You could use array_shift

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

This will remove the first row.

your code becomes:

$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;

Upvotes: 0

kittycat
kittycat

Reputation: 15045

The easiest way to do this is to just remove the first line like so:

$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;

Here we extract only the contents after from the first CRLF \r\n to the end of the data. Then we left trim the CRLF out and thus have removed the first line.

Upvotes: 4

m4t1t0
m4t1t0

Reputation: 5721

Saddly there is no way to do pass a parameter to function csv_from_result and avoid the column names, but you can build your custom csv_from_result function based on the code of the original function an removing the undesired part:

/**
* 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;
}

The code is based on the implementation of csv_from_result taken from here: https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_utility.php

Upvotes: 1

Related Questions