I have code which download the excel file.
I want to save this file in folder.
if($array_count > 0)
{
$fileName = "export_data" . rand(1,100) . ".xls";
if ($error_array) {
function filterData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($error_array as $row) {
if(!$flag) {
// display column names as first row
// echo implode("\t", array_keys($row)). "\r\n";;
$flag = true;
}
// filter data
//header_remove('require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php")');
array_walk($row, 'filterData');
echo implode("\t", array_values($row)). "\r\n"; ;
}
//exit;
}
}
Please some one help me to change my code to save file in folder.
Here I have made one sample for you with static array data. We can save the file in the folder.
You can make changes in this code as per your requirement.
<?php
$data_array = array (
array ('1','2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$sep = "\t";
$xls = "col1".$sep."col2 \n";//Column headers
foreach ($data_array as $record){
$xls.= $record[0].$sep.$record[1]."\n"; //Append data to xls
}
$xls_handler = fopen ('xlsfile.xls','w');
fwrite ($xls_handler,$xls);
fclose ($xls_handler);
echo 'Data saved to xlsfile.xls';
?>
Im currently trying to write a few words on a file, and then open it.
currently, i do have the following outcome:
When my desired outcome would be something like:
How come it is like that?
TextAr is just some numbers from a textarea. ( one id each line)
code:
$text = preg_replace('/\n+/', "\n", trim($_POST['ids']));
$textAr = explode("\n", $text);
foreach ($textAr as $k=>$v) if(empty(trim($v))) unset($textAr[$k]);
$textAr = array_filter($textAr, 'trim');
$handle = fopen("file.txt", "w");
$saveresult = '';
foreach ($textAr as $line) {
$line = str_replace(' ', '', $line);
$line = preg_replace('/\D/', '', $line);
$result = httpPost($url, $line);
$showID = ($showID ? "".$result['id']." -" : '');
$notexisting = ($showasnull ? 0 : "N/A");
if ($result['manual'] == true) {
$saveresult .= "".$showID." Manual".PHP_EOL;
}
if ($result['hit'] == true && $result['manual'] != true) {
$saveresult .= "".$showID." " . $result['price'] . "".PHP_EOL;
} else if ($result['hit'] == false) {
$saveresult .= "".$showID." ".$notexisting."".PHP_EOL;
}
$saveresult .= "\r\n";
?>
<?PHP }
fwrite($handle, $saveresult);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
EDIT
i removed $saveresult .= "\r\n"; but still same result.
EDIT 2:
example of textAr:
array(2) { [0]=> string(8) "43631132" [1]=> string(8) "43631132" }
example of $result
array(4) { ["id"]=> string(8) "43631132" ["price"]=> int(0) ["hit"]=> bool(false) ["manual"]=> bool(false) }
You can write each line independantly. This way you can check if the line itself is empty before writing.
foreach ($textAr as $line) {
$saveresult = "";
$line = str_replace(' ', '', $line);
$line = preg_replace('/\D/', '', $line);
$result = httpPost($url, $line);
$showID = ($showID ? "".$result['id']." -" : '');
$notexisting = ($showasnull ? 0 : "N/A");
if ($result['manual'] == true) {
$saveresult .= "".$showID." Manual";
}
if ($result['hit'] == true && $result['manual'] != true) {
$saveresult .= "".$showID." " . $result['price'];
} else if ($result['hit'] == false) {
$saveresult .= "".$showID." ".$notexisting;
}
$saveresult = trim($saveresult);
if (!empty($saveresult)) {
fwrite($handle, $saveresult.PHP_EOL);
}
}
fclose($handle);
i am trying to convert pdf file to excel.
So first i have fetched the data from pdf and adding that to excel
when i have hard-coded the values then it is working file but i want code without hard-coding my code is:-
$result = pdf2text ('1.pdf');
$array1 = explode('***', $result );
function filterData(&$str) {
$str = preg_replace("/\t/", "\t", $str); $str = preg_replace("/\r? \n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; }
$data = array(
array($array1[0]),
array($array1[1]),
array($array1[2])
);
$fileName = "codexworld_export_data" . date('Ymd') . ".xls";
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
foreach($data as $row) {
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}
exit;
above code is working fine but i don't want to mention array1 as $array1[0],$array1[1],$array1[2].
because my pdf file may have multiple values also so please tell me how to assign $array1 to $data
Try Like this..
$array1 =array('aaa',22);//an assumed array
foreach ($array1 as $key=>$value)
{
$data[] = array($value);
}
print_r($data);
is there any other way to extract serialized data from sql to excel? I tried to do this
<?php
$hostname_dbconnect = "localhost";
$database_dbconnect = "upload_dodwnload";
$username_dbconnect = "root";
$password_dbconnect = "";
$dbconnect = mysql_pconnect($hostname_dbconnect, $username_dbconnect, $password_dbconnect) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
$query = "SELECT * FROM tbl_emp_sched";
$result = mysql_query($query) or die ("no query");
$row_try=mysql_fetch_array($result);
$numrows=mysql_num_rows($result);
/*
$empid=unserialize($row_try['Employee_ID']);
$empname=unserialize($row_try['Emp_FullName']);
$empwrk=unserialize($row_try['Emp_WrkFrcCode']);
$empsch=unserialize($row_try['Emp_SchdCode']);
$datas= array(
"0" => $empid,
"1" => $empname,
"2" => $empwrk,
"3" => $empsch
);
print_r ($datas);
*/
$array_try = array($result['Employee_ID'],$result['Emp_FullName'],$result['Emp_WrkFrcCode'],$result['Emp_SchdCode']);
while($datas = mysql_fetch_array($result))
{
$array_try[] = $datas;
}
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$filename = "Rota_Schedule_(Schedule Codes)" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($array_try as $datas) {
if(!$flag) {
echo implode("\t", array_keys($datas)) . "\n";
$flag = true;
}
array_walk($datas, 'cleanData');
echo implode("\t", array_values($datas)) . "\n";
}
?>
but i don't get what i want. Anybody can help me? This problem causing me hours and hours of testing, any other idea? I tried to unserialize it first but the code just gone crazy and not working properly. Anybody can help me? Thanks
I'm trying to convert an array of products into a CSV file, but it doesn't seem to be going to plan. The CSV file is one long line, here is my code:
for($i=0;$i<count($prods);$i++) {
$sql = "SELECT * FROM products WHERE id = '".$prods[$i]."'";
$result = $mysqli->query($sql);
$info = $result->fetch_array();
}
$header = '';
for($i=0;$i<count($info);$i++)
{
$row = $info[$i];
$line = '';
for($b=0;$b<count($row);$b++)
{
$value = $row[$b];
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
array_to_CSV($data);
function array_to_CSV($data)
{
$outstream = fopen("php://output", 'r+');
fputcsv($outstream, $data, ',', '"');
rewind($outstream);
$csv = fgets($outstream);
fclose($outstream);
return $csv;
}
Also, the header doesn't force a download. I've been copy and pasting the output and saving as .csv
EDIT
PROBLEM RESOLVED:
If anyone else was looking for the same thing, found a better way of doing it:
$num = 0;
$sql = "SELECT id, name, description FROM products";
if($result = $mysqli->query($sql)) {
while($p = $result->fetch_array()) {
$prod[$num]['id'] = $p['id'];
$prod[$num]['name'] = $p['name'];
$prod[$num]['description'] = $p['description'];
$num++;
}
}
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=pressurecsv.csv");
fputcsv($output, array('id','name','description'));
foreach($prod as $product) {
fputcsv($output, $product);
}
fclose($output) or die("Can't close php://output");
Instead of writing out values consider using fputcsv().
This may solve your problem immediately.
Note from comment: I should mention that this will be making a file on your server, so you'll need to read that file's contents before outputting it, also if you don't want to save a copy then you'll need to ùnlink`the file when you are done
This is a simple solution that exports an array to csv string:
function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $item) {
fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
}
rewind($f);
return stream_get_contents($f);
}
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));
Reference
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
how to write unified new line in PHP?
I know this is old, I had a case where I needed the array key to be included in the CSV also, so I updated the script by Jesse Q to do that.
I used a string as output, as implode can't add new line (new line is something I added, and should really be there).
Please note, this only works with single value arrays (key, value). but could easily be updated to handle multi-dimensional (key, array()).
function arrayToCsv( array &$fields, $delimiter = ',', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = '';
foreach ( $fields as $key => $field ) {
if ($field === null && $nullToMysqlNull) {
$output = '';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output .= $key;
$output .= $delimiter;
$output .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
$output .= PHP_EOL;
}
else {
$output .= $key;
$output .= $delimiter;
$output .= $field;
$output .= PHP_EOL;
}
}
return $output ;
}
In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:
function array2csv($array, &$title, &$data) {
foreach($array as $key => $value) {
if(is_array($value)) {
$title .= $key . ",";
$data .= "" . ",";
array2csv($value, $title, $data);
} else {
$title .= $key . ",";
$data .= '"' . $value . '",';
}
}
}
Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:
agentid fname lname empid totals sales leads dish dishnet top200_plus top120 latino base_packages
G-adriana ADRIANA EUGENIA PALOMO PAIZ 886 0 19 0 0 0 0 0
You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:
$title .= $key . ",";
$data .= "" . ",";
after the is_array() to compact the code further and remove the extra column.
Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:
$title .= PHP_EOL;
$data .= PHP_EOL;
Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.
The easiest way to create csv file from an array is to use implode() function:
<?php
$arr = array('A','B','C','D');
echo implode(",",$arr);
?>
The output of the above code will give:
A,B,C,D
Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php
It worked for me.
$f=fopen('php://memory','w');
$header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );
fputcsv($f,$header);
fputcsv($f,$header);
fputcsv($f,$header);
fseek($f,0);
header('content-type:text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);```
I use this simple function to create every single array entry as csv:
function arrayToCsv($fields, $delimiter = ",", $enclosure = "\"", $escapeChar = "\"")
{
$fp = fopen('php://temp', 'r+');
fputcsv($fp, $fields, $delimiter, $enclosure, $escapeChar);
rewind($fp);
$ret = fgets($fp);
fclose($fp);
return $ret;
}
You can try below code to export csv from array using fputcsv
ob_start();
$outputCsv = fopen('php://output', 'w');
fputcsv($outputCsv, ['column 1', 'column 2' 'column 3'], ",");
fputcsv($outputCsv, ['','',''], ",");
fputcsv($outputCsv, ['value 1', 'value 2' 'value 3'], ",");
fputcsv($outputCsv, ['value 11', 'value 21' 'value 31'], ",");
fputcsv($outputCsv, ['value 12', 'value 22' 'value 31'], ",");
header('Cache-Control: max-age=0');
header("Expires: 0");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-type: application/csv');
header('Content-Disposition: attachment;filename="doc_logs.csv"');
header("Content-Transfer-Encoding: binary");
fpassthru($outputCsv);
fclose($outputCsv);