I have a function in PHP that aims to download a csv file, but there is always a blank line at the start of the file
How to delete the blank line at the beginning of the file
this is my code
$name_file = 'ekspor-kag-bri-' . date('Ym', strtotime($data_pendukung['tgl_trf'])) . '.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$name_file.'"');
$kata_header = "REKENING;NOMINAL;EMAIL"."\n";
$kata_header .= "tes";
$arr_isi_cell = [];
foreach ($dt_gaji as $row) {
$isi_cell = str_replace("-","",$row->norekening) . ';' . floatval($row->total_gaji) . ';' . 'inayohanes#gmail.com'."\n";
array_push($arr_isi_cell,$isi_cell);
}
$myfile = fopen("php://output", "wb");
fwrite($myfile,$kata_header);
foreach($arr_isi_cell as $line){
// fputcsv($myfile,explode(',',$line),",");
fwrite($myfile,$line);
}
fclose($myfile)
Related
I'm trying to generate a csv file with PHP and one column contains a cash value. I'd like to add a '£' sign before the number - but everything I have tried, and everything I've found on Stackoverflow doesn't seem to help and the Excel output always has a strange character infront of the £ symbol (see below).
I have pasted some of my code here (I've taken out other rows which were not relevant). Can anyone let me know what I'm doing wrong?
$output = fopen('php://output', 'w');
fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
fputcsv( $output, array('Cash collected'));
$i = 0;
foreach ($quizzes as $key => $value) {
$i++;
$poundsign = html_entity_decode('£', ENT_QUOTES | ENT_XML1, 'utf-8');
$modified_values = array(
$poundsign . $value->quiz_cash,
);
);
fputcsv( $output, $modified_values );
}
fclose($output);
$dest_output = 'output.csv';
$output_size = filesize($dest_output);
header("Content-Type: text/csv; charset=utf-8");
if(isset($_GET['brwry']) || $_GET['brwry'] == NULL):
$filename = '' . $brewerytitle;
else:
$filename = 'All breweries';
endif;
header("Content-Disposition: attachment; filename=\"" . $filename . " " . $_GET['start'] . " - " . $_GET['end'] . ".csv\";" );
header("Content-Length: " . $output_size);
readfile($dest_output);
exit;
Thanks,
Lloyd
I'm trying to export several tables from a database and creating a excel file for each table using PHP. The loop however is "bugged". Instead of creating a new file for each loop it just puts all data into the same file.
The code:
foreach ($pdo->query("SHOW TABLES;") as $allTables) {
$table = $allTables[0];
$allDataStmt = $pdo->prepare("SELECT * FROM $table;");
$allDataStmt->execute();
$fieldcount = $allDataStmt->columnCount();
$col_title = "";
$data = "";
for ($i = 0; $i < $fieldcount; $i++) {
$col = $allDataStmt->getColumnMeta($i);
$column = $col['name'];
$col_title .= '<Cell ss:StyleID="2"><Data ss:Type="String">' . $column . '</Data></Cell>';
}
$col_title = '<Row>' . $col_title . '</Row>';
while ($row = $allDataStmt->fetch(PDO::FETCH_NUM)) {
$line = '';
foreach ($row as $value) {
if ((!isset($value)) or ($value == "")) {
$value = '<Cell ss:StyleID="1"><Data ss:Type="String"></Data></Cell>\t';
} else {
$value = str_replace('"', '', $value);
$value = '<Cell ss:StyleID="1"><Data ss:Type="String">' . $value . '</Data></Cell>\t';
}
$line .= $value;
}
$data .= trim("<Row>" . $line . "</Row>") . "\n";
}
$data = str_replace("\r", "", $data);
header("Content-Type: application/vnd.ms-excel;");
header("Content-Disposition: attachment; filename=" . $table . ".xls");
header("Pragma: no-cache");
header("Expires: 0");
}
}
If I kill the loop after the first iteration it exports the data correctly from ONE table. If I let the loop run it just loads the same file with the data and the file becomes corrupted. I can't even open it in Excel.
What am I missing? Been stuck with this for hours.
Thank you!
What you are attempting with making multiple different attachments in the same HTTP request is not possible. The HTTP protocol does not have support for downloading multiple files. The most common workaround is to put the files in a zip archive for the client to download, so something like this:
$zip = new ZipArchive;
$zip_name = "excel_tables.zip";
if ($zip->open($zip_name, ZipArchive::CREATE|ZipArchive::OVERWRITE) === TRUE) {
foreach ($pdo->query("SHOW TABLES;") as $allTables) {
// (Your logic to build Excel file)
$file_content = $col_title . "\n" . $data;
$file_name = $table . ".xls";
file_put_contents($file_name, $file_content);
// Add file to the zip file
$zip->addFile($file_name);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . $zip_name);
header("Content-Length: " . filesize($zip_name));
header("Pragma: no-cache");
header("Expires: 0");
ob_clean();
flush();
readfile(__DIR__ . "/" . $zip_name);
}
I am trying to zip and download files (pdf) in wordpress. It works fine in the root directory. But not working inside wp-content>themes>functions.php. It gets downloaded and on opening, it shows **archive is either unknown format or damaged**. Permission given 777. Help me please
Code: (this works in folder from root directory)
inside foreach loop i get the $file. But file_get_contents doesnt work
$i = 0;
$files[$i]['download'] = 'http://live.ifireup.com/wp-content/uploads/signed_forms/signed_form_4787.pdf';
$files[$i]['name'] = "signed_form_" . $i . date('YmdHis') . ".pdf";
$i = 1;
$files[$i]['download'] = 'http://live.ifireup.com/wp-content/uploads/signed_forms/signed_form_4787.pdf';
$files[$i]['name'] = "signed_form1_" . $i . date('YmdHis') . ".pdf";
$tmpFile = tempnam('/tmp', '');
$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
// download file
$fileContent = file_get_contents($file['download']);
$zip->addFromString(basename($file['name']), $fileContent);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=SignedForms.zip');
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
unlink($tmpFile);
exit;
Ok so I found this off somewhere this website and I tried this but it is just spamming my console with a ton of errors, I don't get what I'm doing wrong
<?php
set_time_limit(0);
$dirPath = "masked on purpose";
$songCode = $_REQUEST['c'];
$filePath = $dirPath . "/" . $songCode . ".mp3";
$bitrate = 128;
$strContext=stream_context_create(
array(
'http'=>array(
'method'=>'GET',
'header'=>"Accept-language: en\r\n"
)
)
);
header('Content-type: audio/mpeg');
header ("Content-Transfer-Encoding: binary");
header ("Pragma: no-cache");
header ("icy-br: " . $bitrate);
$fpOrigin=fopen($filePath, 'rb', false, $strContext);
while(!feof($fpOrigin)){
$buffer=fread($fpOrigin, 4096);
echo $buffer;
flush();
}
fclose($fpOrigin);
?>
What I'm trying to do is to make an online radio stream that scans a folder, and loops all the .mp3 files in it
An edit here:
I've changed the script to look like this
<?php
set_time_limit(0);
$dirPath = "...";
$bitrate = 128;
$strContext=stream_context_create(
array(
'http'=>array(
'method'=>'GET',
'header'=>"Accept-language: en\r\n"
)
)
);
header('Content-type: audio/mpeg');
header ("Content-Transfer-Encoding: binary");
header ("Pragma: no-cache");
header ("icy-br: " . $bitrate);
$list = scandir($dirPath);
foreach($list as $file)
{
if($file== '.' or $file== '..')
continue; // skip, not a file or a folder
if(is_dir($file))
continue; // skip, not a file
echo $file . "<br>";
// define the file path
$filePath = $dirPath . '/' . $file;
// read the file
$fh = fopen($filePath, "r") or die("Could not open file.");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
echo $buffer;
flush();
}
fclose($fh);
}
}
?>
The code works fine but the problem is that I want the stream to continue even when no one is listening to it, it restarts each time someone tries to listen to it.
The fopen function will return a resource to the opened file or a FALSE boolean value if it fails. Looks like your file is failing to open. Check if the $filePath is correct and that $songCode has a value.
Here is a code to read all files in a folder:
// get a list of all files/folders in a path
$list = scandir($dirPath);
foreach($list as $file)
{
if($file== '.' or $file== '..')
continue; // skip, not a file or a folder
if(is_dir($file))
continue; // skip, not a file
// define the file path
$filePath = $dirPath . '/' . $file;
// read the file
$fh = fopen($filePath, "r") or die("Could not open file.");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
// Do something with the buffer here...
}
fclose($fh);
}
}
I have the below code, where I generate random numbers and try to download them as a CSV file.
If I try the CSV code snippet alone on a different file it works, but in this code, it just does not work. I do see the random numbers echoed, but it does not download the CSV file.
<?php
$dataarray=array();
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
foreach ($input_array as $line)
{
fputcsv($temp_memory, $line, $delimiter);
}
fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}
for ($i = 0; $i <= 25000; $i++)
{
$num = (rand(50,110));
array_push($dataarray,"$num");
echo "Hearbeat #" .$i . "\t\t ------ " . $num;
echo "<br>";
}
convert_to_csv($dataarray, 'data_as_csv.csv', ',');
?>
Outputting data before sending headers with header() means that header() calls will have no effect. So it is reasonable not to send anything before headers.
As another answer mentioned - second argument to fputcsv must be array, so I changed the call to fputcsv too.
If you want all values to written to csv file with comma as separator - pass $input_array directly to fputcsv.
So, your code can look like:
<?php
$dataarray=array();
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
// Option 1 - every number will be on a new line
foreach ($input_array as $line)
{
// add `array($line)` not `$line`
fputcsv($temp_memory, array($line), $delimiter);
}
// Option 2 - all numbers will be in
// one line with `$delimiter` as separator
fputcsv($temp_memory, $input_array, $delimiter);
fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}
for ($i = 0; $i <= 25000; $i++)
{
$num = (rand(50,110));
array_push($dataarray,"$num");
// this two lines are nor needed
//echo "Hearbeat #" .$i . "\t\t ------ " . $num;
//echo "<br>";
}
convert_to_csv($dataarray, 'data_as_csv.csv', ',');
Actually, the problem is in your convert_to_csv function.
fputcsv expects the second parameter to be an array, and in you case is a string. You have 2 options depending on what you want:
1) Each number in a separate line: just change the fputcsv function call to: fputcsv($temp_memory, [$line], $delimiter);
2) All numbers in the same line separated by $delimiter:
function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
fputcsv($temp_memory, $fields, $delimiter);
fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}
And (I'm sure you already know), for the file to be downloaded automatically you must not echo anything.