Check Field data before exporting to CSV format

Description PHP

This function takes a string, and checks to see if it needs to be wrapped in double quotes. This is important for CSV files.

Each field is seperated by a comma, but if the data in that field contains a comma, it needs to be quoted. Also, because of those quotes, if the field data contains a quote it needs to be escaped (by adding another quote directly after it).

You would perform this function for every field in the row, not once for the entire row.

The Code Download

  1. <?php
  2. function checkCsvQuotes($string) {
  3.     if (strpos($string,'"') !== false) {
  4.         return '"'.str_replace('"','""',$string).'"';
  5.     } elseif (strpos($string,',') !== false) {
  6.         return '"'.$string.'"';
  7.     } else {
  8.         return $string;
  9.     }
  10. }
  11. ?>

Credits

Added by JC on 14th January 2008

Comments

There are no comments about this snippet.

Post Comment Github Markdown Supported

You must be logged in to post a comment.

Login here to post a comment