Export database to CSV with columns PHP - php

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.

Related

generate pipe delimited file through codeigniter

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

Export data to CSV file with php and simple html dom

How to export grabbed data to .csv file? I'm using php simple html dom to parse data. Here is the code:
foreach ($linkoviStranica as $stranica)
{
$podaciStranice = "http://someurl/$stranica";
$data = file_get_html($podaciStranice);
$name = $data->find('div[class="price-card-name-header-name"]');
$onlinePrice = $data->find('div[class="price-box online"]');
$diffPrice = $data->find('div[class="price-box paper"]');
echo "<strong>".$name[0]->innertext."<strong>"."<br>";
if (!empty($onlinePrice[0]->innertext))
{
echo $onlinePrice[0]->innertext."<br>";
}
if (!empty($diffPrice[0]->innertext))
{
echo $diffPrice[0]->innertext."<br>";
echo "---------------------"."<br>";
}
}
I want to export, $name, $onlinePrice, $diffPrice to csv file with header in the following format:
name onlinePrice diffPrice
example 10 44
xxxx 412 461
zzzzz 1414 41
Could you please help me? Thanks!
Something like this:
// Define a array to hold all the data
$data = [];
// OR use this line if you want the headers with names on the first line of the file
// $data = [['name', 'onlinePrice', 'diffPrice']];
// Loop the raw data
foreach ($linkoviStranica as $stranica) {
$podaciStranice = "http://someurl/$stranica";
$data = file_get_html($podaciStranice);
$name = $data->find('div[class="price-card-name-header-name"]');
$onlinePrice = $data->find('div[class="price-box online"]');
$diffPrice = $data->find('div[class="price-box paper"]');
// Add current row to out array
$data[] = [
$name[0]->innertext,
$onlinePrice[0]->innertext,
$diffPrice[0]->innertext
];
}
// Open a new file. Replace the file name with the name you'd like
$fp = fopen('file.csv', 'w');
// Loop each row in the data array
foreach ($data as $fields) {
// This method converts a row to a CSV line (http://php.net/manual/en/function.fputcsv.php)
fputcsv($fp, $fields);
}
// Close the file handler
fclose($fp);
$header ="SNo , Order Date , Order Number , Compaign , Amount , Order Status , Used Date , Cancel Reason , Order Commision , Payment Date , Payment Status \n";
$header1 =$header ;
$result='';
foreach ($data as $fields) {
$result= 'echo your data with coma seprated '."\n";
}
$all=$header.$result;
$name="report.csv";
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$name);
header("Pragma: no-cache");
header("Expires: 0");
print "$header1 $result";

how to convert php file into csv

$lang['add_a']="Add a";
$lang['ban_zon_link']="Banner, Zone linking";
$lang['ban_zon_link_help']="Zones linking with Banners";
$lang['manage_ban_zon_link_help']="Manage banner zone linking -";
$lang['adtag']="Ad Tag";
I saved above lines into php file as lang.php need to convert php file into csv in code level.
You could open the file as csv, iterate over your array and use fputcsv
foreach($lang as $myrow) {
fputcsv($output, $myrow);
}
http://php.net/manual/en/function.fputcsv.php
You can use fputcsv:
<?php
$lang = ...
$fp = fopen('file.csv', 'w');
// Insert array keys as CSV header
fputcsv($fp, array_keys($lang);
// Insert values as first data row
fputcsv($fp, array_values($fields));
fclose($fp);
?>
This works if you have only row record in your $lang array as your example suggests. This will create a 2 rows CSV with an header (the keys of the $lang array) and one data row (the values of the array.
If you are aiming at a different thing please clarify your question.
include("lang.php");
foreach($lang as $l)
{
file_put_contents("csv_file.csv",$l.",",FILE_APPEND);
// csv_file.csv is the name of your file
}
file_put_contents("csv_file.csv","\n",FILE_APPEND);
try with this:-
/* $lang['add_a']="Add a";
$lang['ban_zon_link']="Banner, Zone linking";
$lang['ban_zon_link_help']="Zones linking with Banners";
$lang['manage_ban_zon_link_help']="Manage banner zone linking -";
$lang['adtag']="Ad Tag";*/
if above php code in lang.php:-
require_once "lang.php";
$fp = fopen('file.csv', 'w');
fputcsv($fp, array_keys($lang));
fputcsv($fp, array_values($lang));
fclose($fp);
To read in a PHP script and write it out, I've done the following...
<?php
$file="part1.php";
$outFile="part1.csv";
$in = file($file);
$out = fopen($outFile, "w");
foreach($in as $line ) {
$parts = explode("=", $line);
if ( count($parts) == 2 ) {
fputcsv($out, array($parts[0],"=",rtrim($parts[1],";".PHP_EOL)));
}
}
fclose($out);
which for your example ( as part1.php) gives...
$lang['add_a'],=,"""Add a"""
$lang['ban_zon_link'],=,"""Banner, Zone linking"""
$lang['ban_zon_link_help'],=,"""Zones linking with Banners"""
$lang['manage_ban_zon_link_help'],=,"""Manage banner zone linking -"""
$lang['adtag'],=,"""Ad Tag"""
$file = 'file.csv';
header( "Content-Type: text/csv;charset=utf-8" );
header( "Content-Disposition: attachment;filename=\"$file\"" );
header("Pragma: no-cache");
header("Expires: 0");
$fp= fopen('php://output', 'w');
foreach ($lang as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
exit();

PHP not creating downloadable CSV file

I am trying to pull out data from my database using php and exporting it into a downloadable CSV file that can be opened with excel. I am able to do this when i use mysql however, many have advised to not include mysql syntax in my code as its being deprecated and instead i should use mysqli. I have changed my code but now my code is not working. Does anyone know why that is?
mysql version (working version)`
mysql_connect('localhost', 'xxxxx', 'xxxxx') or die('connect');
mysql_select_db('db') or die('select');
$result = mysql_query('SELECT * bodyshops_master_network') or die('query');
if(mysql_num_rows($result) == 0)
{
die('no data');
}
$fh = tmpfile() or die('tmpfile');
$cols = array_keys(mysql_fetch_assoc($result));
fputcsv($fh, $cols);
mysql_data_seek($result, 0); // set result row pointer back to first row
while($row = mysql_fetch_assoc($result))
{
fputcsv($fh, $row);
}
rewind($fh);
$text = fread($fh, 999999);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="download.csv"');
header('Content-Length: ' . strlen($text));
echo $text;
exit;
mysqli version (not working):
$mysqli = new mysqli("localhost", "xxxxx", "xxxxx", "db");
if (mysqli_connect_errno())
{
printf("Connect failed: ", mysqli_connect_error());
exit();
} else
{
$result = "SELECT * FROM bodyshops_master_network";
if(mysqli_num_rows($result) == 0)
{
die('no data');
}
$fh = tmpfile() or die('tmpfile');
$cols = array_keys($result->fetch_assoc());
fputcsv($fh, $cols);
$result->data_seek(0); // set result row pointer back to first row
while($row = $result->fetch_assoc())
{
fputcsv($fh, $row);
}
rewind($fh);
$text = fread($fh, 999999);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="download.csv"');
header('Content-Length: ' . strlen($text));
echo $text;
exit;
Check phpinfo to see that mysqli extension is enabled.
Remove/comment the header calls so that you receive the output as plain HTML so that you notice if any message shows up (due to die or coding error) or if you actually get the data.
Also note that you loose the date of the first record you retrieve because you call:
$cols = array_keys(mysql_fetch_assoc($result));
respectively
$cols = array_keys($result->fetch_assoc());
What is not working?
Are you getting any errors?
Is the file empty, is there any file downloading?
Maybe errors aren't enabled, try this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
I'm new on StackOverflow, I think this would help. (I speak spanish, I hope you to understand my english :D )
I've been looking for a simply way to use mysqli and download a csv file that could be read by excel without UTF-8 problems (using ñ,á,ü...). I didn't found it, so I created one by myself (learning from Google and StackOverflow answers), after some hours I got something that works finally.
This is a Class that connects with the database and the functions will do whatever you want using mysqli and PHP. In this case, calling this class (require or include), just use the "downloadCsv()" function.
As an example, this would be the "class.php" file:
<?php
class DB{
private $con;
//this constructor connects with the database
public function __construct(){
$this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName");
if($this->con->connect_errno > 0){
die('There was a problem [' . $con->connect_error . ']');
}
}
//create the function that will download a csv file from a mysqli query
public function downloadCsv(){
$count = 0;
$header = "";
$data = "";
//query
$result = $this->con->query("SELECT * FROM Your_TableName");
//count fields
$count = $result->field_count;
//columns names
$names = $result->fetch_fields();
//put column names into header
foreach($names as $value) {
$header .= $value->name.";";
}
}
//put rows from your query
while($row = $result->fetch_row()) {
$line = '';
foreach($row as $value) {
if(!isset($value) || $value == "") {
$value = ";"; //in this case, ";" separates columns
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too
}
$line .= $value;
} //end foreach
$data .= trim($line)."\n";
} //end while
//avoiding problems with data that includes "\r"
$data = str_replace("\r", "", $data);
//if empty query
if ($data == "") {
$data = "\nno matching records found\n";
}
$count = $result->field_count;
//Download csv file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=FILENAME.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $header."\n".$data."\n";
}
?>
After creating the "class.php" file, in this example, use that function on "download.php" file:
<?php
//call the "class.php" file
require_once 'class.php';
//instantiate DB class
$export = new DB();
//call function
$export->downloadCsv();
?>
After download, open the file with MS Excel.
I hope this help you, I think I wrote it well, I didn't feel comfortable with the text and code field.

Generate pipe delimited file through php

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('...'), '|');

Categories