EllisLab text mark
Advanced Search
     
CI 2.1 / csv_from_result() / Trailing Delimiter
Posted: 25 October 2012 08:12 PM   [ Ignore ]
Avatar
Joined: 2012-10-25
5 posts

Hi, folks. While using the csv_from_result function, I noticed that each line had an extra delimiter (a comma) at the end of the line.

For example:
“Birth Date”,“Record Creation Date”,“Record Last Update”,

Checking the code for csv_from_result (system/database/DB_utility.php, line 222), it appears that this is intentional:

foreach ($row as $item)
   
{
      $out 
.= $enclosure.str_replace($enclosure$enclosure.$enclosureitem).$enclosure.$delim;
   
}
   $out 
rtrim($out);
   
$out .= $newline

I would expect that the last delimiter would be removed before the adding the newline character.

Any thoughts?  Thanks.

 

 
Posted: 26 October 2012 07:09 AM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2012-10-25
5 posts

I added the following to routine csv_from_result() to remove the trailing delimiter:

function 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 
'';
      
$len_delim strlen($delim);  // delimiter may be multiple characters

      // First generate the headings from the table column names
      
foreach ($query->list_fields() as $name)
      
{
         $out 
.= $enclosure.str_replace($enclosure$enclosure.$enclosure$name).$enclosure.$delim;
      
}

      $out 
rtrim($out);
      
$out substr($out0, -$len_delim); // remove trailing delimiter from header
      
$out .= $newline;
      
      
// Next blast through the result array and build out the rows
      
foreach ($query->result_array() as $row)
      
{
         
foreach ($row as $item)
         
{
            $out 
.= $enclosure.str_replace($enclosure$enclosure.$enclosure$item).$enclosure.$delim;
         
}
         $out 
rtrim($out);
         
$out substr($out0, -$len_delim);  // remove trailing delimiter
         
$out .= $newline;
      
}
      
      
return $out;
   

I still think the original code, which contains a trailing delimiter, is a bug. Any thoughts?

Thanks.