fwrite result PHP - php

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);

Related

How to add the results of a sql oracle query in a csv file in php?

I have a php code that I connect to an oracle database and with a request to retrieve the information I want, here is my code :
$query = "SELECT ACTIVE_SIZES FROM ADA_ACTIVE_SIZE2_VIEW WHERE ADA_STYLE = 'SCPCL4'";
$result = odbc_exec($connect, $query);
while($final = odbc_fetch_array($result)) {
print_r($final); //Array ( [ACTIVE_SIZES] => XS-S-M-L-XL-2XL )
}
Now I'm reading a csv file and I would like to adapt this code to add the results of my queries in a column at the end of the file. I already add two columns at the end of this one, but my query doesn't return anything in the csv file, how can I do please?
<?php
//Modifications on csv file
$delimiter = ";";
$csv_data = array();
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
//Add two columns at the end
$data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
$data['Color-Description'] = (!empty($data[3]) ? (ltrim($data[4], '0') ?: '') . "-" . $data[3] : '');
//Query
$query = "SELECT ACTIVE_SIZES FROM ADA_ACTIVE_SIZE2_VIEW WHERE ADA_STYLE = '".$data[4]."'";
$result = odbc_exec($connect, $query);
while($final = odbc_fetch_array($result)) {
$data['Sizes'] = $final;
var_dump($final); //array(1) { ["ACTIVE_SIZES"]=> string(8) "XS-S-M-L" }array(1) { ["ACTIVE_SIZES"]=> string(8) "XS-S-M-L" }...
}
$csv_data[] = $data;
var_dump($csv_data); //["Pictures Names"]=> string(15) "SCJEG4_1041.jpg" ["Color-Description"]=> string(12) "1041-MUSTARD" ["Sizes"]=> array(1) { ["ACTIVE_SIZES"]=> string(15) "XS-S-M-L-XL-2XL" } } }
}
fclose($handle);
}
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}
?>
At the end I have this in my csv file:
Try this, only thing is you need to define your ActiveSizes index and push it to the sizes index
$delimiter = ";";
$csv_data = array();
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
//Add two columns at the end
$data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
$data['Color-Description'] = (!empty($data[3]) ? (ltrim($data[4], '0') ?: '') . "-" . $data[3] : '');
//Query
$query = "SELECT ACTIVE_SIZES FROM ADA_ACTIVE_SIZE2_VIEW WHERE ADA_STYLE = '".$data[4]."'";
$result = odbc_exec($connect, $query);
while($row = odbc_fetch_array($result)) {
$data['Sizes'][] = $row['ACTIVE_SIZES'];
}
$csv_data[] = $data;
}
fclose($handle);
}
//var_dump($csv_data);
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}

Php-imap_open-How can I show a link to save attachment, without save files on server?

I tried to fetchbody to read emails from imap_open connection.
I can read the text of the mail and I can save all attachments on my Webserver.
But I want to create a link for everyone attachment-file, to download the files directly from the mail-Server, without save files on my Webserver.
I want:
Link—>Download—>direct from Mail-Server
At this moment:
Save all attachments on my Webserver—> link to each file on my Webserver—> Download attachments from my Webserver
<?php
If ((Isset($_POST['uid']) == false) or (Isset($_POST['user']) == false) or (Isset($_POST['pw']) == false)) {
echo ("Keine Zuordnung vorhanden");
return;
}
function getAttachments($imap, $mailNum, $part, $partNum) {
$attachments = array();
if (isset($part->parts)) {
foreach ($part->parts as $key => $subpart) {
if($partNum != "") {
$newPartNum = $partNum . "." . ($key + 1);
}
else {
$newPartNum = ($key+1);
}
$result = getAttachments($imap, $mailNum, $subpart,
$newPartNum);
if (count($result) != 0) {
array_push($attachments, $result);
}
}
}
else if (isset($part->disposition)) {
// print_r($part);
if (strtoupper($part->disposition) == "ATTACHMENT") {
$partStruct = imap_bodystruct($imap, $mailNum, $partNum);
$attachmentDetails = array(
"name" => $part->dparameters[0]->value,
"subtype" => $partStruct->subtype,
"partNum" => $partNum,
"enc" => $partStruct->encoding
);
return $attachmentDetails;
}
}
return $attachments;
}
function getPartList($struct, $base="") {
$res=Array();
if (!property_exists($struct,"parts")) {
return [$base?:"0"];
} else {
$num=1;
if (count($struct->parts)==1) return getPartList($struct->parts[0], $base);
foreach ($struct->parts as $p=>$part) {
foreach (getPartList($part, $p+1) as $subpart) {
$res[]=($base?"$base.":"").$subpart;
}
}
}
return $res;
}
$username = $_POST['user'] ;
$pw = $_POST['pw'];
$server_in = $_POST['server'];
$port = $_POST['port'];
$uid = $_POST['uid'];
$msgno = $_POST['msgno'];
$imap= imap_open($server_in, $username, $pw);
$msgno = imap_msgno($imap, $uid);
$nachrichten_struktur = imap_fetchstructure($imap, $uid, FT_UID);
$kodierung = $nachrichten_struktur->encoding;
$nachrichten_type = $nachrichten_struktur->type;
$res=getPartList($nachrichten_struktur);
if ($nachrichten_type == 0){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno ,1));
}
else if ($nachrichten_type == 1){
if(count($res) <=2){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 2));
}
else if(count($res) >=3){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 2.2));
}
}
else{
$text = imap_fetchbody($imap, $msgno ,1);
}
switch ($kodierung) {
# 7BIT
case 0:
$body = $text;
# 8BIT
case 1:
$body = quoted_printable_decode(imap_8bit($text));
# BINARY
case 2:
$body = imap_binary($text);
# BASE64
case 3:
$body = imap_base64($text);
# QUOTED-PRINTABLE
case 4:
$body = quoted_printable_decode($text);
# OTHER
case 5:
$body = $text;
# UNKNOWN
default:
$body = $text;
}
//attachmentDetails
$attachments = getAttachments($imap, $msgno, $nachrichten_struktur, "");
$body .= "<br />Attachments: ";
$body .= "<ul>";
foreach ($attachments as $attachment) {
$body .= '<li>' .$attachment["name"] . "</li>";
}
$body .= "</ul>";
echo $body;
imap_close($imap);
?>
Sorry, but i hadn't soo much time last few days.
I solved my problem. The right way is:
Read Email, check attachments -> write a submit link for every attachment file, AND input hidden filed which has part_number and uid_number -> click on link, send form to php file -> php file read attachment from webserver and give it back via content type:
header("Content-Type: application/octet-stream");
header("Content-Type: application/force-download");
My read file:
....
function getAttachments($imap, $mailNum, $part, $partNum) {
$attachments = array();
if (isset($part->parts)) {
foreach ($part->parts as $key => $subpart) {
if($partNum != "") {
$newPartNum = $partNum . "." . ($key + 1);
}
else {
$newPartNum = ($key+1);
}
$result = getAttachments($imap, $mailNum, $subpart,
$newPartNum);
if (count($result) != 0) {
array_push($attachments, $result);
}
}
}
else if (isset($part->disposition)) {
// print_r($part);
if (strtoupper($part->disposition) == "ATTACHMENT") {
$partStruct = imap_bodystruct($imap, $mailNum, $partNum);
$attachmentDetails = array(
"name" => $part->dparameters[0]->value,
"subtype" => $partStruct->subtype,
"partNum" => $partNum,
"enc" => $partStruct->encoding
);
return $attachmentDetails;
}
}
return $attachments;
}
function getPartList($struct, $base="") {
$res=Array();
if (!property_exists($struct,"parts")) {
return [$base?:"0"];
} else {
$num=1;
if (count($struct->parts)==1) return getPartList($struct->parts[0], $base);
foreach ($struct->parts as $p=>$part) {
foreach (getPartList($part, $p+1) as $subpart) {
$res[]=($base?"$base.":"").$subpart;
}
}
}
return $res;
}
$imap= imap_open($server_in, $username, $pw);
$msgno = imap_msgno($imap, $uid);
$nachrichten_struktur = imap_fetchstructure($imap, $uid, FT_UID);
$kodierung = $nachrichten_struktur->encoding;
$nachrichten_type = $nachrichten_struktur->type;
$res=getPartList($nachrichten_struktur);
$subtype = $nachrichten_struktur->subtype;
if ($nachrichten_type == 0){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno ,1));
}
else if ($nachrichten_type == 1){
if(count($res) <=2){
if ($subtype == "MIXED"){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 1));
}
else{
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 2));
}
}
else if(count($res) >=3){
$text = quoted_printable_decode(imap_fetchbody($imap, $msgno , 1));
}
}
else{
$text = imap_fetchbody($imap, $msgno ,1);
}
switch ($kodierung) {
# 7BIT
case 0:
$body = $text;
# 8BIT
case 1:
$body = quoted_printable_decode(imap_8bit($text));
# BINARY
case 2:
$body = imap_binary($text);
# BASE64
case 3:
$body = imap_base64($text);
# QUOTED-PRINTABLE
case 4:
$body = quoted_printable_decode($text);
# OTHER
case 5:
$body = $text;
# UNKNOWN
default:
$body = $text;
}
//attachmentDetails
$attachments = getAttachments($imap, $msgno, $nachrichten_struktur, "");
if(count($attachments) > 0){
$body .= "<br />Attachments: <br /> ";
}
foreach ($attachments as $attachment) {
$body .= "<span style='display:inline-block; margin-right:1%;'><form class='form_download_attachment' action='src/php/download_attach.php' method='POST' target='_blank'>";
$body .= "<input type='hidden' name='uid' value='".$uid."'>";
$body .= "<input type='hidden' name='data-attachment_partNum' value='".$attachment["partNum"]."'>";
$body .= "<input type='hidden' name='data-enc' value='".$attachment["enc"]."'>";
//$body .= "<input type='hidden' name='server' value='".$server_in."'>";
//$body .= "<input type='hidden' name='user' value='".$username."'>";
//$body .= "<input type='hidden' name='pw' value='".$pw."'>";
$body .= '<button type="submit" class="attachment_download btn btn-warning btn-sm" >' .$attachment["name"] . "</button>";
$body .= "</form></span>";
}
....
my download file:
...
$imap_open= imap_open($get_server_in, $get_username, $get_pw);
$msgno = imap_msgno($imap_open, $get_uid);
function downloadAttachment($imap, $uid, $partNum, $encoding) {
$partStruct = imap_bodystruct($imap, imap_msgno($imap, $uid), $partNum);
$filesize = $partStruct->bytes;
$filename = $partStruct->dparameters[0]->value;
$message = imap_fetchbody($imap, $uid, $partNum, FT_UID);
switch ($encoding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
$message = imap_base64($message);
break;
case 4:
$message = quoted_printable_decode($message);
break;
}
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Transfer-Encoding: binary");
if ($_SESSION['mobile'] != "true"){
header("Content-Length: ".$filesize);
}
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Pragma: public");
echo $message;
}
downloadAttachment($imap_open, $get_uid, $get_partNum, $get_encoding);
...
Thank for your help!

How to PHP Export Serialized Data to Excel

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

php to excel encoding

hello i have this code to export my data from to .xls but i have problem with encoding, this is my code
<?php
header("Content-Type: text/plain;charset=UTF-8");
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
$data = array(
array('firstname' =>'Name', 'last_name' => 'Last Name', 'age' => '25'),
array('firstname' =>'name 2', 'last_name' => 'Last Name 2', 'age' => '27')
);
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>
I try the Encoding iso-8859-7, and windows-1253, and UTF-8 i want to export with greek characters all my data is in UTF-8. Thank you for help
<?php
include('connect.php');
header("Content-Type: text/plain; charset=UTF-8");
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv; charset=UTF-8");
$out = fopen("php://output", 'w');
$flag = false;
$result = mysql_query("SELECT * FROM categories ORDER BY id") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
?>
I change my code and in text editor i can see my characters is fine and the encoding is in greek, but when i open in microsoft excel it's unreadable

PHP Array to CSV

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);

Categories