• PHP Help PHP Coding
  • [RESOLVED] Problem would like to have/view csv files in Excel with line breaks within a "cell"?

Hi; Here is the problem. I know how to query a database and create a page that will open directly in Excel rather than in a browser. (ie. the output is formatted as .csv)

However, I have some field values that, when excel opens, I want to have them all within a single cell of the excel/csv display, BUT with within-cell line breaks. Get it?

Say I have a field value that returns something like this:

"RespChoices=1:Yes|2:No|3:Unsure"
I would like the cell to display something like this:

RespChoices=
1:Yes
2:No
3:Unsure

(there may be other cells on the same line with more or fewer response choices)

<?php
session_start();
foreach($_GET as $var=>$val) {$$var=$val;}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$extr_date=date('mdY'); 
$TITLE="$SRV_".$extr_date;
header("content-disposition: attachment;filename=$TITLE.csv");
// the items/response key headers for the spreadsheet
$lines = file("".$SRV.".qst"); // Load the file into an array 
$_SESSION[$SRV][item]="\"\",\"\""; // a couple of blank cells for row values that always exist
$_SESSION[$SRV][respkey]="\"respdate\",\"rowkey\"";
foreach ($lines as $key =>$value) {     
if(substr($value, 0,1)=="Q") {$_SESSION[$SRV][item].=",\"$value\"";} elseif(substr($value, 0,1)=="S"){$_SESSION[$SRV][respkey].=",\"$value\"";} else {} // not needed } $_SESSION[$SRV][item].="\n"; $_SESSION[$SRV][respkey].="\n"; echo $_SESSION[$SRV][item]; echo $_SESSION[$SRV][respkey]; // the actual data include("../data/".$SRV.".dat"); ?>

Any ideas? Thanks.

    It's easy to find out by simple inspection.

    If you save an excel sheet like this one

    	1
    A	a1
    B	a2
    C	a3
    	a4
    D
    

    as CSV, you will get

    a1
    a2
    "a3
    a4"
    

    So all you need to do is enclose cells containing line breaks in double quotes.

    And if you ask yourself how to handle cells with double quotes and line breaks, just save such a spreadsheet as CSV to find out that double quotes are escaped with double quotes. I.e.

    	1
    A	a1
    B	a2
    C	a3"
    	a4"
    D
    

    becomes

    a1
    a2
    "a3""
    a4"""
    

    If your text editor can't tell you what character is used for line breaks, some simple php code will tell you that.

    $s = file_get_contents('./linebreaks.csv');
    
    for ($i = 0; $i < strlen($s); ++$i)
    {
    	printf('<pre>%d: %s%s</pre>', ord($s[$i]), $s[$i], PHP_EOL);
    }
    

    output

    97: a
    
    49: 1
    
    13: 
    
    97: a
    
    50: 2
    
    13: 
    
    34: "
    
    97: a
    
    51: 3
    
    34: "
    
    34: "
    
    13: 
    
    97: a
    
    52: 4
    
    34: "
    
    34: "
    
    34: "
    

    Which tells you that cell breaks and inter-cell linebreaks are both handled by the character with decimal value 13, also known as Carriage Return, CR or 0xD.

    At least on my OS and version of Excel. I'd double check to be certain, but I'm guessing the format will stay the same between OS and Excel versions.

      Okay...this is a little more abstract than I was after but it IS very helpful. I see that my pipe characters (|) have a value of 124.

      So if the content of my field value is a string such as:
      "RespChoices=1:Yes|2:No|3:Unsure"

      ...is there a way to then automatically convert these pipes to a character or characters that will function as the within-cell line breaks I am looking for?

        replace pipes with the new line char looks like 13 via str_replace before output?

        $str = "content to put|into csv file|and stuff you know?";
        $str = str_replace(chr(124),chr(13),$str);
        

          That seems to be getting me closer, but instead of the text actually breaking within the cell where the pipe was, I see a little box with a question mark inside of it (it is opening in Excel2007 on this computer)...I will try some other character substitutions. Is there a chr() value the corresponds to Excel's Alt-ENTER key combination in this context?

          Hmmmm maybe johanafm's suggestion can help me figure that out.

            I have no idea heh, I was just using chr(13) based on the info in Johanafm's post.

              On a whim I tried chr(10) in place of chr(13) and it seems to do exactly what I want! Thank you all so much!🙂

                Write a Reply...