From 7dcd7a3aa4b145fc8a040c16e7c4de9ea35fd5cf Mon Sep 17 00:00:00 2001 From: Derek Allard Date: Thu, 12 Jul 2007 12:36:50 +0000 Subject: csv_from_result() move robust against data with "," in it. --- system/database/DB_utility.php | 54 +++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 19 deletions(-) (limited to 'system/database') diff --git a/system/database/DB_utility.php b/system/database/DB_utility.php index d48425d7e..8ce19b17f 100644 --- a/system/database/DB_utility.php +++ b/system/database/DB_utility.php @@ -236,35 +236,51 @@ class CI_DB_utility { * @param string The newline character - \n by default * @return string */ - function csv_from_result($query, $delim = "\t", $newline = "\n") + function csv_from_result($query, $delim = ',', $newline = '', $enclosure = '"') { - if ( ! is_object($query) OR ! method_exists($query, 'field_names')) - { - show_error('You must submit a valid result object'); - } + if (!is_a($query, 'CI_DB_result')) { + show_error('CI_DB_utility::csv_from_result - You must submit a valid result object'); + } + + if ($delim === '') { + show_error('CI_DB_utility::csv_from_result - Empty delimiters are not permitted'); + } + + if ($newline === '') { + $newline = (stripos(getenv('HTTP_USER_AGENT'), 'win') !== false) ? "\r\n" : "\n"; + } + if ((strpos($enclosure, $newline) !== false) or (($enclosure !== '') and (strpos($newline, $enclosure) !== false))) { + show_error('CI_DB_utility::csv_from_result - Field enclosure must not be contained within delimiter (or vice versa)'); + } + $out = ''; // First generate the headings from the table column names - foreach ($query->list_fields() as $name) - { - $out .= $name.$delim; + foreach ($query->list_fields() as $name) { + // there's no point enclosing strings that do not require it + if (strpos($name, $delim) !== false) { + $out .= $enclosure . $name . $enclosure . $delim; + } else { + $out .= $name . $delim; + } } - $out = rtrim($out); - $out .= $newline; - + $out = rtrim($out, $delim) . $newline; + // Next blast through the result array and build out the rows - foreach ($query->result_array() as $row) - { - foreach ($row as $item) - { - $out .= $item.$delim; + foreach ($query->result_array() as $row) { + foreach ($row as $item) { + // there's no point enclosing strings that do not require it + if (strpos($item, $delim) !== false) { + $out .= $enclosure . $item . $enclosure . $delim; + } else { + $out .= $item . $delim; + } } - $out = rtrim($out); - $out .= $newline; + $out = rtrim($out, $delim) . $newline; } - + return $out; } -- cgit v1.2.3-24-g4f1b