Skip to content

Instantly share code, notes, and snippets.

@Flushot
Created June 14, 2013 22:31
Show Gist options
  • Select an option

  • Save Flushot/5785793 to your computer and use it in GitHub Desktop.

Select an option

Save Flushot/5785793 to your computer and use it in GitHub Desktop.
Transforms a hash table into a CSV. This is useful for dumping results from database queries. Includes an optional row transformer, which can pre-process rows with complex computations (such as decryption).
<?php namespace chrisl\utils;
function transform_csv(
$rows,
array $cols=[],
Closure $row_transformer=null,
array $opts=[
'skip_header' => false,
'col_sep' => ',',
'quote' => '"',
'escape' => '\\'
'line_ending' => '\n']) {
$csv_rows = [];
if (!$opts['skip_header'])
$csv_rows[] = $opts['quote'].join($cols, $opts['quote'].$opts['col_sep'].$opts['quote']).$opts['quote'];
foreach ($rows as $row) { // each result row
if ($row_transformer) $row = $row_transformer($row, $cols);
$col_count = count($cols);
$csv_row = '';
for ($i = 0; $i < $col_count; ++$i) { // each column
$col = $cols[$i]; // column name
$csv_row .= $opts['quote'] .
str_replace($opts['quote'], $opts['escape'].$opts['quote'], $row[$col]) .
$opts['quote'];
if ($i < $col_count - 1)
$csv_row .= $opts['col_sep'];
}
$csv_rows[] = $csv_row;
}
return join($csv_rows, $opts['line_ending']) .
$opts['line_ending'];
}
// Example use case
require 'crypt';
$db = new \mysql('server', 'user', 'pass', 'db');
$crypt = new Crypt();
print transform_csv(
$db->query('select * from users order by first_name limit 20')->fetch_assoc(), // rows
[ 'id', 'first_name', 'last_name', 'password' ], // columns (to extract)
function($row, $cols) { // transform row (optional)
// decrypt encrypted columns
$decrypted_row = [];
$encrypted_cols = array_intersect($cols, ['password']);
for ($i = 0; $i < count($cols); ++$i) {
$cell = $row[$cols[$i]];
if (in_array($cols[$i], $encrypted_cols)) { // column is encrypted
try { $cell = $crypt->decrypt($cell); }
catch (CryptException $ex) { $cell = 'ERROR'; }
}
$decrypted_row[] = $cell;
}
return $decrypted_row;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment