Home  >  Q&A  >  body text

Print new lines into cells of CSV file

<p>I am using php to generate a CSV file. I need to print text wrap within a cell (in Excel you can use <kbd>Ctrl</kbd> <kbd>Enter</kbd> or <kbd>Alt</kbd> <kbd>Enter</ kbd>implementation). For this I tried using <code>'n'</code>, <code>'r'</code> but it didn't help. How can I achieve this? </p> <p>I am using yii extension ECSVExport to generate csv. </p> <p>The output I want is as follows: </p> <pre class="brush:php;toolbar:false;">ID Value 1A B 2C 3E FF G 4 X</pre> <p><br /></p>
P粉276577460P粉276577460445 days ago579

reply all(2)I'll reply

  • P粉022723606

    P粉0227236062023-08-23 15:46:59

    Use "\n" within the cell value (wrapped with ") and use "\r\n" as the end of record tag. If If the cell input contains multiple lines, must be surrounded by ".

    $fh = fopen('test1.csv', 'w+');
    fwrite($fh, "sep=\t" . "\r\n");
    fwrite($fh, 'A' ."\t" . 'B' . "\t" . 'C' . "\r\n");
    fwrite($fh, 'D' ."\t" . "\"E\nF\nG\"" . "\t" . 'H' . "\r\n");
    fclose($fh);

    or (use variable)

    $varA = 'A';
    $varB = 'B';
    $varC = 'C';
    $varD = 'D';
    $varE = 'E';
    $varF = 'F';
    $varG = 'G';
    $varH = 'H';
    $fh = fopen('test2.csv', 'w+');
    fwrite($fh, "sep=\t"."\r\n");
    fwrite($fh, $varA . "\t" . $varB . "\t" . $varC . "\r\n");
    fwrite($fh, $varD . "\t" . "\"$varE\n$varF\n$varG\"" . "\t" . $varH . "\r\n");
    fclose($fh);

    or (use fputcsv())

    $fh = fopen('test3.csv', 'w+');
    fwrite($fh, "sep=\t" . "\r\n");
    fputcsv($fh, array('A', 'B', 'C'), "\t");
    fputcsv($fh, array('D', "E\nF\nG", 'H'), "\t");
    fclose($fh);

    or (using

    fputcsv() and variables)

    $varA = 'A';
    $varB = 'B';
    $varC = 'C';
    $varD = 'D';
    $varE = 'E';
    $varF = 'F';
    $varG = 'G';
    $varH = 'H';
    $fh = fopen('test4.csv', 'w+');
    fwrite($fh, "sep=\t" . "\r\n");
    fputcsv($fh, array($varA, $varB, $varC), "\t");
    fputcsv($fh, array($varD, "$varE\n$varF\n$varG", $varH), "\t");
    fclose($fh);

    reply
    0
  • P粉409742142

    P粉4097421422023-08-23 10:28:46

    Try this

    "\n"

    Within double quotes

    reply
    0
  • Cancelreply