I am using the below for csv export but i want to export as a pipe delimeted output text file format.
My code generates a txt file using PHP's fputcsv function.
For the delimiter, I am trying to use '|'.
this mycode:
function to_CSV($table) {
$file_csv = "file_csv.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='htmltable' AND TABLE_NAME='$table'";
$result = mysqli_query(db_connect(),$query);
while ($row = mysqli_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$file_csv);
fputcsv($fp, $header);
$query ="SELECT * from $table";
$result = mysqli_query(db_connect(),$query);
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
}
fclose($fp);
$contents = file_get_contents($file_csv);
$contents = str_replace(",", "|", $contents);
file_put_contents($file_csv, $contents);
How to implementation in codeigniter. help me out please.
thanks a lot.
according to the docs fputcsv format line as CSV and write to file pointer, it has a third parameter which expects a delimiter - take a look at
https://www.php.net/manual/en/function.fputcsv
In your case it means
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row, '|');
}
however the main question is - if you use Codeigniter as underlying Framework - why dont you use the model principle and aside of that the provided query builder? - it will make your life much easier.
You can find more informations in their very well written documentation. Take a look at https://codeigniter.com/user_guide/general/models.html?highlight=model
Related
Following is a part of my php program which is written to fetch rows from mysql table from input IDs. But I wanted to get the result directly to '.csv' file. I know php has built in function for that, but I could not include it effectively. So can anyone give a direction for export to csv using advanced php function?
$file = fopen("fetched.csv","w");
for($i=0;$i<=$len;$i++)
{
$lo = $locus[$i];
mysqli_select_db($conn,"microarray");
$query = mysqli_query("SELECT * FROM anatomy WHERE locus_id = "$lo"");
while ($row = mysqli_fetch_row($query))
{
}
}
You don't necessarily need an "advanced php function". A csv file is just a sequence of comma separated columns. Try this out.
function addRowToCsv(& $csvString, $cols) {
$csvString = implode(',', $cols) . PHP_EOL;
}
$csvString = '';
$first = true;
while ($row = mysqli_fetch_assoc($query)) {
if ($first === true) {
$first = false;
addRowToCsv($csvString, array_keys($row));
}
addRowToCsv($csvString, $row);
}
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');
echo $csvString;
Notice that the first argument to addRowToCsv is passed by reference. This is not required and you could easily use a return value, but this is just how I would do it.
-- Edit --
I just noticed you are saving the output to a file rather than serving it as a download. If that is what you want to do then use the above but replace
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyCsvFile.csv');
echo $csvString;
With..
file_put_contents('MyCsvFile.csv', $csvString);
Here my php script to export database info to CSV file.
I dont arrive to put any structure to correctly tidy my infos in my CSV file.
For example, put all names in a name column, all emails in an email column... etc
include_once('conf.php');
include_once('BDD.php');
header('charset=UTF-8');
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$bdd = new BDD($conf['bddhost'], $conf['bddport'], $conf['bddname'], $conf['bdduser'], $conf['bddpass']);
$sql = "SELECT * FROM user";
$qry = $bdd->prepare($sql);
// Execute the statement
$qry->execute();
$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
// Export every row to a file
fputcsv($data, $row);
echo ''.$row['prenom'].' '
.$row['nom'].' '
.$row['email'].' '
.$row['cp'].' '
.$row['information'].'
';
}
fclose($data);
You don't want to use echo as you are creating the file with fputcsv
while ($row = $qry->fetch(PDO::FETCH_ASSOC))
{
// Export every row to a file
fputcsv($data, $row);
}
// reset the file pointer to the beginning of the file
rewind($data);
// dump the csv file and stop the script
fpassthru($data);
exit;
Syntax errors:
$data = fopen('/tmp/db_user_export_".time().".csv', 'w');
^-- ^-- ^-- ^---
You're mixing string quoting styles, so your filename is literally going to contain the characters ", ., t, etc... in it.
Try
$data = fopen('/tmp/db_user_export_' .time() .'.csv', 'w');
^----------^---
instead. Note the change from " -> '.
Since your result is an array, this may help you out:
Convert php array to csv string
if(!function_exists('str_putcsv'))
{
function str_putcsv($input, $delimiter = ',', $enclosure = '"')
{
// Open a memory "file" for read/write...
$fp = fopen('php://temp', 'r+');
// ... write the $input array to the "file" using fputcsv()...
fputcsv($fp, $input, $delimiter, $enclosure);
// ... rewind the "file" so we can read what we just wrote...
rewind($fp);
// ... read the entire line into a variable...
$data = fread($fp, 1048576);
// ... close the "file"...
fclose($fp);
// ... and return the $data to the caller, with the trailing newline from fgets() removed.
return rtrim($data, "\n");
}
}
$csvString = '';
foreach ($list as $fields) {
$csvString .= str_putcsv($fp, $fields);
}
More about this on GitHub, a function created by #johanmeiring.
I don't have a lot of experience with using the fputcsv function.
I'm trying to make a function, by which an admin can download a file with all the user information.
The CSV should be generated in this way :
Serial Number Username Email etc etc
And then the records from a query.
I have this function which I'm using to generate the csv file :
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And then I call the function:
<?php
include 'inc/inc.functions.php';
include 'dbconnector.php';
$query="SELECT * from users order by email LIMIT 0,30";
$result=mysql_query($query,$db) or die(mysql_error($db));
$array=mysql_fetch_array($result);
foreach($array as $arr)
{
array_to_csv_download($arr,"records.csv",":");
}
?>
The CSV generated displays: Warning, Invalid argument supplied for foreach.
What should I do to display in the way I require?
UPDATE
http://i.imgur.com/2xH0gT1.png
You're currently calling your function for a single row in the database, rather than for the entire result set. The following should use your function correctly:
$query = "SELECT * from users order by email LIMIT 0,30";
$result = mysql_query($query,$db) or die(mysql_error($db));
$array = array();
# Headers
$array[] = array("Serial Number","Username","Email","etc etc");
while($row = mysql_fetch_row($result)) {
$array[] = $row;
}
array_to_csv_download($array,"records.csv",":");
I'm sure this is simple for someone else, but it escapes me.
I have a function that generates a .csv file based on a query input from an internal website.
The problem is, for speed purposes, I want to run 1 query to save to two different arrays. One of which I can pass to a function, the other to use for printing a table.
I've tried to pass the same $result var to the function. It seems to strip the data once sent through function? I need some help.
code for function:
function save_to_csv($result1, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result1 = mysql_query($query1) or die( mysql_error() );
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result1);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result1, 0);
}
}
while($row = mysql_fetch_assoc($result1)) {
fputcsv($fp, $row);
}
fclose($fp);
}
I've tried setting second array like so
$csv_result = array();
also tried
$csv_result = $result = mysql_query($query);
I'm assuming it's something here, but I just cant see it.
There's nothing in this code that demonstrates why you need two separate arrays. After the line where you set $result1, you can simply do the following for the exact same effect:
$row = mysql_fetch_assoc($result1);
if ($row) {
if ($headers) {
fputcsv($fp, array_keys($row));
}
fputcsv($fp, $row);
}
The variable $row hasn't been modified, and is still equal to the data retrieved from $query1. There's really no need to make a duplicate array unless one of them is going to be modified. However, if you want to make a copy of the data at any point, you can just use:
$new_copy = $row;
My code generates a txt file using PHP's fputcsv function.
For the delimiter, I am trying to use '|'
$query = mysql_query("SELECT email, emailSource FROM session WHERE is_complete='1' ORDER by sessionid ASC")
$filename= 'here.txt';
$fp = fopen( $filename,'w');
fputcsv($fp, array('Email address', 'Email Source'));
if(mysql_numrows($query) > 0) {
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
fputcsv($fp, array_values($row));
}
}
fclose($fp);
$contents = file_get_contents($filename);
$contents = str_replace(",", "|", $contents);
file_put_contents($filename, $contents);
The result I get is all on one line instead of showing the values on a seperate line and I also have "" around the headers.
"Email address"|"Email Source"|blah#blah.com|hi|
instead of this:
Email address|Email Source|
blah#blah.com|hi|
Please can someone tell me what I am doing wrong. Is it because I am using fputcsv and saving to a txt file?
Get rid of the str_replace / file_get_contents/ file_put_contents block. Instead of fputcsv($fp, array('...')), use fputcsv($fp, array('...'), '|');