Trying to add a line break in output file from a string - php

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!

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;

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>' . "
";
};

Related

How to format output of system function PHP?

I use function system() to run system process.
$buff = system('python excel.py ' . $handle->file_dst_pathname, $retval);
It displays messages in line without separations.
In Python I use this line to print data:
print "# %d - article \"%s\" was inserted!" % (i, article)
Precede the output of system(...); with echo "<pre>"; and follow with echo "</pre>";
Or shorter:
$buff = "<pre>" . system('python excel.py ' . $handle->file_dst_pathname, $retval) . "</pre>";
You could also change all the "\n" chars of your output into "<br/>".

Control output being sent while it's being processed

I've implemented a file optimization script which takes about 30 seconds or more. There's a loop in which I added echos to track what's being processed.
However, most of the time, no output is being sent, until the end of the process.
How can I control this in order to send the echos in an iteration just as they're being finished?
EDIT:
This is the implied code, with the output buffer functions:
set_time_limit(60);
ini_set("memory_limit", "256M");
$documents = $this->documents_model->get($date1, $date2);
ob_start();
echo '-- Start ' . "<br>\n";
ob_end_flush();
flush();
foreach ($documents as $document) {
ob_start();
echo '-- Processing document ' . $document->id . "<br>\n";
$file = $document->get_file_name();
if (! $file || ! file_exists(DOCUMENT_ROOT . 'documents/' . $file)) {
echo '---- Document ' . $document->id . " has no PDF file yet or it was deleted<br>\n";
$path = $this->documents_model->generatePDF($document);
echo '------ file generated: ' . $path;
}
ob_end_flush();
flush();
}
echo '-- End ' . "<br>\n";
The reason why you will get the output after the processing finishes, is php's output buffer and eventually your webserver's buffer.
You will have to flush these buffers with the invokation of ob_flush() and flush() after every few echo statements.
For more technical information see PHP buffer ob_flush() vs. flush()

Adding PHP Line Spaces In Codeigniter

I am trying to write file but just need to work out best way to make some gaps/spaces between some code “[‘default’][‘hostname’]” space . ‘=’ . space “‘localhost’”can not work it out.
At the moment when reload page it produces $db['default']['hostname']='localhost'; but need gap/space $db['default']['hostname'] = 'localhost';
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index(){
$output = '<?php' . "\n";
$output .= "\n";
$output .= '// DB' . "\n";
$output .= '$db' . "['default']['hostname']" space . '=' . space "'localhost'". ";" . "\n";
$file = fopen(APPPATH . 'config/database-test.php', 'w');
fwrite($file, $output);
fclose($file);
$this->load->view('welcome_message');
}
}
$output .= '$db' . "['default']['hostname']" space . '=' . space "'localhost'". ";" . "\n";
This line has syntax errors because you're missing the concat operator before the first space and after the second one (whatever the space is meant to be).
Instead of complicating things, why don't you just write this and avoid the concat hell:
$output .= '$db' . "['default']['hostname'] = 'localhost';\n";
I think I have found answer to make gap . " " . seems to do the trick.
$output .= '$db' . "['default']['hostname']" . " " . '=' . " " . "'localhost'". ";" . "\n";
As an additional note, I see you are writing a config file to be processed later.
I have found output buffering and var_export to do this job exceptionally well.
ob_start();
var_export($config);
$out = ob_get_clean();
then
fwrite($f, '$config = '.$out.';'); etc...
http://us3.php.net/manual/en/function.ob-get-clean.php
http://us3.php.net/manual/en/function.var-export.php
basically this will turn an array into a parse-able string such as
array(
'default'=>array(
'hostname'=>'localhost',
'user' => 'user', ///etc
)
)
then just add the variable part and the ending semi-colon
if you plan to do multiple values this would be a much cleaner approach

php generating excel and downloading

i have a website with one simple function to generate an excel with array data and then offers user to download.
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
the code above was used to test, but I only get some html code from the website in the excel, not the data.
May I ask why it happens?
Thanks!
Make sure you don't send anything before header calls.
// At the begginnig of script...
ob_start();
// ... do some stuff ...
ob_get_clean();
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
die();
Another approach if you need to process entire script:
<?php
// At the beggining...
ob_start();
$content="";
$normalout=true;
// ... do some stuff ...
// i guess if some condition is true...
$content=ob_get_clean();
$normalout=false;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
// Here you could die() or continue...
ob_start();
// ... rest of execution ...
$content.=ob_get_clean();
if($normalout)
{
echo($content);
} else {
// Excel provided no output.
}
?>
This should work.
That code seems to work on Chrome without any issue (using php tags, of course).
Here you have a template, anyway, that I use for exporting POST tables that are being sent.
<?php
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
$date = date('Y-m-d-Hi');
header("content-disposition: attachment;filename=Excel_Report_$date.xls");
$table = $_POST["table_info"];
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table>
<tr><th> </th></tr>
<tr><td> </td></tr>
<?=$table?>
</table>
</body>
</html>
If you are exporting some reports that would require some more detail, I would recommend PHPExcel as by far the best library out there for CSV/XML/XLS(X) management via PHP code.
You are sending a file that is a tab-sepparated values, not an XLS (which is a binary format).
What you can do is send the file as a CSV (Content-type="text/csv"), and the file formatted as csv:
header("Content-Type: text/csv");
header("content-disposition: attachment;filename=my_document.csv");
echo '"First Name";"Last Name";"Phone"' . "\n";
echo '"John";"Doe";"555-123456"' . "\n";

How to use php header in Tidesdk

I am trying to generate the force download excel file in my Tidesdk app.So i am trying the following code to work, but it is not working properly.So guys please help me to find out the solution.
<?php
header ("Content-type: application/octet-stream");
header( "Content-disposition: attachment; filename=sheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'Maddy' . "\t" . 'Shan' . "\t" . '555-4445' . "\n";
?>
Just remove
<?php
and
?>
and you should be good to go !

Categories