Search code examples
phpcsvfputcsv

How to export a tab-separated txt file from php array without quotes


I've managed to save a tab-separated file for a product feed with the code below. However, the feed that I am submitting requires that fields are not encased in quotes. Is there a way to save this file out without quotes in the fields.

$feed[]=array('Item','Description','Category');
$feed[]=array('1-1','Words describing item 1, for example.','Top Category > SubCategory1');
$feed[]=array('1-2','Words describing item 2.','Top Category > SubCategory2');

header('Content-type: text/tab-separated-values');
header("Content-Disposition: attachment;filename=bingproductfeed.txt");
$f  =   fopen('php://output', 'a');
foreach ($feed as $fields) {
    //$fields=str_replace('"','',$fields);
    //$fields=trim($fields,'"');
    fputcsv($f, $fields, "\t");
}

//Outputs:
//Item  Description Category
//1-1   "Words describing item 1, for example." "Top Category > SubCategory1"
//1-2   "Words describing item 2."  "Top Category > SubCategory2"

//I need:
//Item  Description Category
//1-1   Words describing item 1, for example.   Top Category > SubCategory1
//1-2   Words describing item 2.    Top Category > SubCategory2

I've tried trimming the quotes out and replacing them with spaces, but no luck there. Is there a way to do this so I can submit this feed without errors?


Solution

  • Based on PHP manual i'd say you can omit the fopen line and simply echo your output directly on the page.

    php://output ¶

    php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.

    So something like this:

    $feed[]=array('Item','Description','Category');
    $feed[]=array('1-1','Words describing item 1, for example.','Top Category > SubCategory1');
    $feed[]=array('1-2','Words describing item 2.','Top Category > SubCategory2');
    
    header('Content-type: text/tab-separated-values');
    header("Content-Disposition: attachment;filename=bingproductfeed.txt");
    foreach ($feed as $fields) {
        //$fields=str_replace('"','',$fields);
        //$fields=trim($fields,'"');
        echo implode("\t",$fields);
    }