#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    530
    Rep Power
    50

    Writing CSV files with fields that include commas


    I am writing a csv file from a MySQL search within a PHP script. The problem is that if the data field includes text with a comma, it acts like a separately delimited field.

    How can I write text that includes a comma without breaking the field? Is there a way of escaping embedded commas?

    My fwrite statement looks like:
    PHP Code:
     fwrite($fileHandle"$company_name$cust_name,  $email$company_address,  $company_city$company_state$company_zip$company_tel$prospect_note \n"); 
    $prospect note may or may not include commas.

    Similarly, the "$company_zip" may include a leading zero and Excel reads it as a number and strips it off when it reads the file. I have solved this by adding a leading apostrophe to the field but that seems clumsy. Is there a better way to handle this

    Thanks
  2. #2
  3. Lazy Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,436
    Rep Power
    9645
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    530
    Rep Power
    50
    Perfect! thanks.

    It appears that fputcsv() is expecting an array, so for each record in my MySQL search, I have the following:
    PHP Code:
    $name_array = array($company_name$cust_name,  $email$company_address$company_city$company_state$company_zip$company_tel$note$lastdate);
      
    fputcsv($fileHandle$name_array); 
    Works a charm!

    Thanks.

    Originally Posted by requinix
    Use fputcsv() instead of fwrite().

IMN logo majestic logo threadwatch logo seochat tools logo