Search code examples
phpfwrite

fwrite dynamic values with commas to excel


I inherited a site and need some help. There is a fwrite() function in php that writes a csv file using information from a database. One of the things I want to be written is a product description. The descriptions all have commas, and when the csv sees the commas, it starts a new cell breaking the description up into many different cells. I would prefer if the entire description was in one cell. I can get it to do that if I str_replace() the commas to something else, so that part of the code isn't the issue.

What's the best way (if it's even possible) to write a value that contains commas to a csv file?

Right now, it looks something like this:

$orderrecord = '"'.$row['product_description_that_has_commas'].'"';

        $orderrecord .= "\r\n";
        $ofl = fopen($exportordersfilename, 'ab');
        fwrite($ofl, $orderrecord);
        fclose($ofl);

Solution

  • Look at the PHP function called fputcsv().

    <?php
    
    $fh = fopen('file', 'w');
    fputcsv($fh, array($description_with_quotes, 'field_two', '...'));
    fclose($fh);