Question

I have PHP saving an output file all from one very long string. I want this code that is being outputted to be formatted properly, so I am trying to add linebreaks in at certain points.. I have been trying to use "\n", but for some reason that is not doing the trick.. Here's the relevant code:

foreach($headerColumn as $hColumn) { 
    $outputString .= '<td>' . $hColumn . '</td>' . "\n";
};

Here I have the "\n" added to the end of the string, but for some reason it is being outputted like this:

<thead>
    <tr><td>Name</td><td>Ticker</td><td>Buy Date</td><td>Current Yield</td>
</tr>
</thead>

When, in actuallity, I want each on its' own line.. any ideas? in case it has something to do with the content type of the file, here is my file write call:

header('Content-Disposition: attachment; filename="sample.txt"');
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient
header('Content-Length: ' . strlen($outputString));
header('Connection: close');

echo $outputString;

Thanks!

Was it helpful?

Solution

I think what you want to use is PHP_EOL:

PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2

So, for your example:

$outputString .= '<td>' . $hColumn . '</td>' . PHP_EOL;

OTHER TIPS

I don't know if this is the best practice... but you can actually put a newline into the code by simply not ending the string quotation until the next line:

foreach($headerColumn as $hColumn) { 
    $outputString .= '<td>' . $hColumn . '</td>' . "
    ";
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top