Write CSV To File Without Enclosures In PHP

前端 未结 14 793
谎友^
谎友^ 2020-12-01 07:11

Is there a native function or solid class/library for writing an array as a line in a CSV file without enclosures? fputcsv will default to \" if no

相关标签:
14条回答
  • 2020-12-01 07:48

    fputcsv($file, $data, ';', chr(127));

    0 讨论(0)
  • 2020-12-01 07:49

    Figured it out. By passing in the ascii code for Null to the car() function it seems to work just fine.

    fputcsv($f, $array, $delimiter, car(0))

    Thanks for the answers everyone!!!

    0 讨论(0)
  • 2020-12-01 07:52

    The downside with a CSV file with no enclosures means an errant comma in user input will munge the row. So you'll need to remove commas before writing a CSV row.

    The tricky part with handling CSV is parsing enclosures, which makes the PHP & PEAR CSV functions valuable. Essentially you're looking for a file that is comma-delimited for columns and newline-delimited for rows. Here's a simple starting point:

    <?php
    $col_separator= ',';
    $row_separator= "\n";
    
    $a= array(
     array('my', 'values', 'are', 'awes,breakit,ome'),
     array('these', 'values', 'also', "rock\nAND\nROLL")
    );
    
    function encodeRow(array $a) {
     global $col_separator;
     global $row_separator;
     // Can't have the separators in the column data!
     $a2= array();
     foreach ($a as $v) {
      $a2[]= str_replace(array($col_separator, $row_separator), '', $v);
     }
     return implode($col_separator, $a2);
    }
    
    $output= array();
    foreach ($a as $row) {
     $output[]= encodeRow($row);
    }
    
    echo(implode($row_separator, $output));
    
    ?>
    
    0 讨论(0)
  • 2020-12-01 07:55

    The warnings about foregoing enclosures are valid, but you've said they don't apply to your use-case.

    I'm wondering why you can't just use something like this?

    <?php
    $fields = array(
        "field 1","field 2","field3hasNoSpaces"
    );
    fputs(STDOUT, implode(',', $fields)."\n");
    
    0 讨论(0)
  • 2020-12-01 07:56

    Doesn't this work?

    fputcsv($fp, split(',', $line),',',' ');
    
    0 讨论(0)
  • 2020-12-01 08:00

    works with chr() function:

    fputcsv($f,$array,',',chr(0));
    
    0 讨论(0)
提交回复
热议问题