I have a MySQL table, from which I create tsv and csv files. I want to create the tsv file whilst adding imaginary headers to the file. I already use the MySQL column headers as the headers for the file, but I need to add extra imaginary headers not in the MySQL table. My current code creates the file, but I do not know how to go about adding the imaginary headers.
It outputs
name age address
Daniel 24 Carlifornia
Jane 22 New York
I want to output
name age address option1 option2
Daniel 24 Carlifornia anything anything
Jane 22 New York anything anything
Here's my code:
#chmod($export_tsv, 0777);
$fe = #fopen($export_tsv."/export.tsv", "w+");
if($fe){
$somecontent = "";
//$somecontent = "header('Content-type: text/html; charset=utf-8')";
$fields_count = 0;
// fields headers
$db->query($sql_view);
if($row = $db->fetchAssoc()){
foreach($row as $key => $val){
if($fields_count++ > 0) $somecontent .= "\t";
// mysql column headers here
$somecontent .= $key;
}
}
$somecontent .= "\r\n";
$db->query($sql_view);
while($row = $db->fetchAssoc()){
$fields_count = 0;
foreach($row as $key => $val){
if($fields_count++ > 0) $somecontent .= "\t";
//my own special code start
$val = str_replace("\n","", $val);
$val = str_replace("\r","", $val);
$val = str_replace("\t","", $val);
$val = stripslashes($val);
$val = str_replace("chr(13)","", $val);
//my own special code end
$somecontent .= $val;
}
$somecontent .= "\r\n";
}
utf8_encode($somecontent);
$somecontent = mb_convert_encoding($somecontent, 'HTML-ENTITIES', "UTF-8");
// write some content to the opened file.
if (fwrite($fe, utf8_encode($somecontent)) == FALSE)
echo 'file_writing_error'." (export.tsv)";
fclose($fe);
}
Maybe you can use the AS keyword in your SQL query?
select something AS `new column name` FROM some_table
Related
I have a problem. I’ve created a web form in HTML that stores data from inputs in CSV file through PHP file using fputcvs function.
Now... When I open that CSV file in Excel, or via =IMPORTDATA function in google sheets, it deletes leading zeros (0). The leading zeros are very important in my case.
Any way or trick to fix it through the PHP or HTML file?
Thanks
My PHP code:
<?php
$fieldA = $_POST["prezime"];
$fieldB = $_POST["ime"];
$fieldC = $_POST["datumrodjenja"];
$fieldD = $_POST["mestorodjenja"];
$fieldE = $_POST["rod"];
$fieldF = $_POST["prebivaliste"];
$fieldG = $_POST["brojpasosa"];
$fieldH = $_POST["izdatod"];
$fieldI = $_POST["vazido"];
$fieldJ = $_POST["profesija"];
$fieldK = $_POST["zanimanje"];
$fieldL = $_POST["fiksni"];
$fieldM = $_POST["mobilni"];
$fieldN = $_POST["email"];
$fieldO = $_POST["napomena"];
$keys = array($fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO); //THIS IS WHERE YOU PUT THE FORM ELEMENTS ex: array('$fieldA','$fieldB',etc)
$keys = ["prezime", "ime", "datumrodjenja", "mestorodjenja", "rod", "prebivaliste",
"brojpasosa", "izdatod", "vazido", "profesija", "zanimanje", "fiksni", "mobilni",
"email", "napomena"];
$labels = ["Prezime", "Ime", "Datum Rođenja", "Mesto Rođenja", "Rod", "Prebivalište",
"Broj Pasoša", "Izdat Od", "Važi Do", "Profesija", "Trenutno Zanimanje", "Tel. Fiksni", "Tel. Mobilni",
"E-mail Adresa", "Napomena"];
$values = [];
foreach ($keys as $key)
$values[] = $_POST[$key];
$fname = 'prijave.csv';
if (!file_exists($fname)) {
$fp = fopen($fname,'a');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($fp, $labels);
}
else {
$fp = fopen($fname,'a');
}
fputcsv($fp, $values);
fclose($fp);
I am trying to export the data from table on SQL server database to the CSV file.
Data is formatted correctly and placed in each separate cells on the file. But the header is not formatted properly and is printed all on to one cell as a continuous stream.
Say you have a,b,c,d as headers :
Header is printed as abcd on to the first cell and is not spitting out on to individual cells. how do we separate them out ?
Here is the code :
$flag = false;
if ($query) {
while( $data = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
foreach($data AS $key => $value){
if(!$flag) {
// display field/column names as first row
$out .= implode("\t", array_keys($data)) . "\n";
//$out .= '"'.$head.'",';
$flag = true;
}
//If the character " exists, then escape it, otherwise the csv file will be invalid.
$pos = strpos($value, '"');
if ($pos !== false) {
$value = str_replace('"', '\"', $value);
}
$out .= '"'.$value.'",';
}
$out .= "\n";
}
$out .= implode("\t", array_keys($data)) . "\n";
Is creating a tab separated line, but elsewhere you are using comma separated.
Probably you want to use comma's here as well:
$out .= implode(",", array_keys($data)) . "\n";
I am trying to make some dynamically made INI files for some GPRS printers. I have the original INI file here and wish to use PHP to make bulk copies of the file with certain changes per printer. I can push the updated INI file to them direct but I am having issues getting the formatting of the INI file right. I have a text file just now with all the settings. I am using this code as a proof of concept but what happens is that it removed all spaces and all line brakes causing it not to work! Is there anyway of getting this to work? Creating an array for all the data (We are talking 75 sections of data. Not all will change per printer mind.)
This is my code:
$replace = array("ID"=>"AC001");
$inifile = 'ini.txt';
$fh = fopen($inifile, 'r');
$inifile = fread($fh, filesize($inifile));
fclose($fh);
foreach($replace as $key => $value)
{
$template = str_replace('{$'.$key.'}', $value, $inifile);
}
echo $template;
$filename = $replace["ID"].".ini";
$handle = fopen($filename, 'x+');
fwrite($handle, $template);
fclose($handle);
Data format:
[section number (1-75)]
Name=Parm name
NameEn=Parm name
Command= Parm (demo case: {$id})
IsValid=1
DataMode=1
IsHide=1
[section number (1-75)]
Name=Parm name
NameEn=Parm name
Command= Parm
IsValid=1
DataMode=1
IsHide=1
What comes out the other side is just one big long line of text.
OK came up with a better option that works! Just now that its broken the string replace function!
function arr2ini(array $a, array $parent = array())
{
$out = '';
foreach ($a as $k => $v)
{
if (is_array($v))
{
//subsection case
//merge all the sections into one array...
$sec = array_merge((array) $parent, (array) $k);
//add section information to the output
$out .= '[' . join('.', $sec) . ']' . PHP_EOL;
//recursively traverse deeper
$out .= arr2ini($v, $sec);
}
else
{
//plain key->value case
$out .= "$k=$v" . PHP_EOL;
}
}
return $out;
}
$replace = array("ID"=>"AC001");
$inifile = 'ini.ini';
$files = parse_ini_file("$inifile",true);
foreach($replace as $key => $value)
{
echo $template = str_replace('{$'.$key.'}', $value, $files);
}
var_dump($template);
$filename = $replace["ID"].".ini";
$ini = arr ; 2ini($template);
echo $ini;
$handle = fopen($filename, 'x+');
fwrite($handle, $ini);
fclose($handle);
I want to read data from text file and group for some data are the same.I have code as below:
$PMTA_DATE = date("Y-m-d");
$PMTA_FILE = file_get_contents("../stats_domain_emetteur_recepteur.affinitead.net.".$PMTA_DATE.".txt");
$lineFromText = explode("\n", $PMTA_FILE);
$result = array();
$cate = "";
$total ="";
$fail = "";
$mailSuc = "";
$title = "";
foreach($lineFromText as $line){
$words = explode(";",$line);
echo $words[5];
echo "<br>";
if($title == ""){
$title = $words[0];
}
$cate .= ','."'$words[6]'";
$total .= ','.$words[7];
$fail .= ','.$words[8];
$mailSuc .= ','.((int)$words[7] - (int)$words[8]);
}
In file data:
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;hotmail.fr;150116;90753;60.45
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;hotmail.com;108478;65766;60.62
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;free.fr;81431;97;.11
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;wanadoo.fr;77786;15;.01
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;gmail.com;77325;1;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;orange.fr;44768;13;.02
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;laposte.net;33844;16;.04
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;neuf.fr;29918;26;.08
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;yahoo.fr;23232;1;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;friendcorp.fr;yahoo.fr;21073;2;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;voila.fr;19692;3;.01
2012-12-19-0830;affinitead.net;1409462;231830;16.44;messengear.fr;free.fr;18234;5;.02
2012-12-19-0830;affinitead.net;1409462;231830;16.44;friendcorp.fr;free.fr;17658;12;.06
2012-12-19-0830;affinitead.net;1409462;231830;16.44;lebuzzdesbonsplans.com;yahoo.fr;15856;103;.64
2012-12-19-0830;affinitead.net;1409462;231830;16.44;cwlunit.com;laposte.net;13463;1;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;msn.com;12044;7222;59.96
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;live.fr;11491;6983;60.76
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;aliceadsl.fr;11145;17;.15
2012-12-19-0830;affinitead.net;1409462;231830;16.44;cwlunit.com;sfr.fr;11135;1;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;tendancity.com;yahoo.fr;10631;0;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;sfr.fr;9878;1;.01
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;club-internet.fr;9868;4;.04
2012-12-19-0830;affinitead.net;1409462;231830;16.44;friendcorp.fr;wanadoo.fr;9533;0;0
2012-12-19-0830;affinitead.net;1409462;231830;16.44;boulevard-des-ventes.com;aol.com;9253;7729;83.52
2012-12-19-0830;affinitead.net;1409462;231830;16.44;lebuzzdesbonsplans.com;hotmail.com;8656;252;2.91
2012-12-19-0830;affinitead.net;1409462;231830;16.44;messengear.fr;laposte.net;8616;1;.01
as you see have some data are the same like boulevard-des-ventes.com it has many time so I don't want that.I want take it only 1 if it has many time.
This is the output I need:
boulevard-des-ventes.com hotmail.fr 150116
hotmail.com 108478
free.fr 81431
..................
..................
..................
friendcorp.fr yahoo.fr 21073
free.fr 17658
cwlunit.com laposte.net 13463
sfr.fr 11135
..................
..................
..................
..................................................
..................................................
..................................................
Use an associative array to remember which domains you've already processed, and skip to the next line when you get a duplicate.
$domains_seen = array();
foreach($lineFromText as $line){
$words = explode(";",$line);
$domain = $words[5];
if array_key_exists($domain, $domains_seen) {
continue;
}
$domains_seen[$domain] = true;
...
}
For example, I have a variable "$foo" that includes all the data which I want to show in the CSV:
$foo = "some value,another value,last value";
My goal is to:
Create a CSV file named "some.csv" whose contents are equal to $foo
Upload "some.csv" to my server.
How can this be done?
Update: Here's the exact code that worked for me.
$foo = "some value,another value,last value";
$file = 'some_data.csv';
file_put_contents($file, $foo);
Number 1:
file_put_contents("foobar.csv", $yourString);
Number 2:
$c = curl_init("http://"...);
curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "#foobar.csv"));
$result = curl_exec($c);
curl_close($c);
print_r($result);
note the # before the filename
See
fputcsv()
If $foo is already csv-formatted. You can use file_put_contents()
You don't specify the upload method. Here is an example using ftp (UNSECURE):
$foo = '...csv data...';
$username = "myUser";
$password = "myPassword";
$url = "myserver.com/file.csv";
$hostname= "ftp://$username:$password#$url";
file_put_contents($hostname, $foo);
If you already have the variable with all the data you can use file_put_contents to save it as a csv
How to upload CSV file using PHP (Working Code)
Query Library
<?php
class query{
function mysql_query_string($string){
$enabled = true;
$htmlspecialchars = false; # Convert special characters to HTML entities
/****************************************************************
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
*****************************************************************/
if($htmlspecialchars){
# Convert special characters to HTML entities
$string = htmlspecialchars($string, ENT_QUOTES);
}
else{
/****************************************************************
'"' (double quote) becomes '"'
''' (single quote) becomes '''
****************************************************************/
//$string = str_replace('"',""",$string);
//$string = str_replace("'","'",$string);
}
if($enabled and gettype($string) == "string"){
# Escapes special characters in a string for use in a SQL statement
return mysql_real_escape_string(trim($string));
}
elseif($enabled and gettype($string) == "array"){
$ary_to_return = array();
foreach($string as $str){
$ary_to_return[]=mysql_real_escape_string(trim($str));
}
return $ary_to_return;
}
else{
return trim($string);
}
}
}
?>
Call Csv Method
public function csvFileSubmitData(){
$this->load->library('query');
$query=new query();
$root = DIR_PATH.'public/administrator/csv/';
$fileToUpload= (isset($_FILES['fileToUpload']) and $_FILES['fileToUpload']['size'] > 0 and
$_FILES['fileToUpload']['error'] == 0) ? $_FILES['fileToUpload'] : "";
if(is_array($fileToUpload)){ # CHECK UPLOADED FILE 1 FOR VALIDATION
$fileToUpload['name'] = str_replace(" ","_",$fileToUpload['name']);
$fileToUpload['name'] = str_replace("&","and",$fileToUpload['name']);
# CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
$fnarr = explode(".", $fileToUpload['name']);
}
$rand = rand(1000,10000);
$filecsv = $rand."_".$fileToUpload['name'];
$file1 = $root.$filecsv;
move_uploaded_file($fileToUpload['tmp_name'],$file1);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = $file1;
$addauto = 0;
$save = 0;
$outputfile = "output.sql";
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 1;
$queries = "";
$linearray = array();
$values = "";
$m =0;
$linestext = split($lineseparator,$csvcontent);
foreach($linestext as $line){
if($m++==0){
continue;
}
$lines++;
$line = trim($line," \t");
if($line == ''){
break;
}
$linearray = explode($fieldseparator,$line);
$topicname = $linearray[0];
$question = $linearray[1];
$answer1 = $linearray[2];
if(isset($linearray[1]) and $linearray[1] != ''){
$topicname = $query->mysql_query_string($linearray[0]);
$question = $query->mysql_query_string($linearray[1]);
$answer_type = $query->mysql_query_string($linearray[2]);
}
//Save Csv data in your table like this
//query(insert into topics SET `topic`='".$topicname."',`question`='".$question."');
}}
If you are using Codeignitor Framework so this code is too easy to integrate ,No hard&fast rule you can also use this code plain PHP as well as .....
Thanx
AbdulSamad
To create the CSV you would need to break your string into an array, then loop through it. After that you can save the file to any directory the web server account has access to on your server. Here is an example ...
//variables for the CSV file
$directory = '/sampledir/';
$file = 'samplefile.csv';
$filepath = $directory.$file;
//open the file
$fp = fopen("$filepath",'w+');
//create the array
$foo = "some value,another value,last value";
$arrFoo = explode(',',$foo);
//loop through the array and write to the file
$buffer = '';
foreach($arrFoo AS $value) {
$buffer .= $value."\r\n";
}
fwrite($fp,$buffer);
//close the file
fclose($fp);
Your file will now be written to the directory set in $directory with the filename set in $file.
-Justin