Keep leading zeros in CSV file through PHP - php

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

Related

Problem with german umlauts in csv file when i write from php

Greeting
I have a problem when I want to use the php script to enter data from the database into the csv file. It prints everything right in the database, but when it prints to the csv file, then it comes to a character error, i.e. does not print them well.
Examples of errors ö, ä, ü ... and what I need ä, ö, ü ....
If I can print somehow to the csv file the way it is in the database?
My code:
<?php
require_once 'connections.php';
$query = "SELECT Artikelnummer_im_Shop, EAN_GTIN_Barcodenummer_UPC,
Herstellerartikelnummern_HAN_MPN, Hersteller_Markenname,
Produktname,Preis_Brutto, Lieferzeit, Produktbeschreibung, ProduktURL,
BildURL_1, Versandkosten, Vorkasse, Paydirekt, Paypal,
Kreditkartenzahlung_uber_BS_PAYONE_GmbH, Versandkosten_Kommentar
FROM app_table";
$result = mysqli_query($connect, $query) or die("database error:".
mysqli_error($connect));
$file = "inko-table.csv";
// Delete file if exist
unlink($file);
// Write to the file or create if not exist
$f = fopen($file, 'w'); // Open in write mode ('w' will overwrite everything everytime)
$table = "app_table";
$sql = mysqli_query($connect, "SELECT * FROM $table");
$num_rows = mysqli_num_rows($sql);
$products = mysqli_fetch_array($sql);
// Writing data in file var $file
$i = 1;
while($row = mysqli_fetch_array($sql)) {
$nameComma = $row['Produktname'];
$name = str_replace(",", "", $nameComma);
$pzn = $row['EAN_GTIN_Barcodenummer_UPC'];
$url = $row['ProduktURL'];
$brand = $row['Hersteller_Markenname'];
$priceComma = $row['Preis_Brutto'];
$price = str_replace(",", ".", $priceComma);
$Artikelnummer = $row['Artikelnummer_im_Shop'];
$ProduktbeschreibungComma = $row['Produktbeschreibung'];
$Produktbeschreibung = str_replace(",", "", $ProduktbeschreibungComma);
$Herstellerartikelnummern = $row['Herstellerartikelnummern_HAN_MPN'];
$LieferzeitComma = $row['Lieferzeit'];
$Lieferzeit = str_replace(",", "", $LieferzeitComma);
$BildURL_1 = $row['BildURL_1'];
$VersandkostenComma = $row['Versandkosten'];
$Versandkosten = str_replace(",", ".", $VersandkostenComma);
$Vorkasse = $row['Vorkasse'];
$Paydirekt = $row['Paydirekt'];
$Paypal = $row['Paypal'];
$Kreditkartenzahlung = $row['Kreditkartenzahlung_uber_BS_PAYONE_GmbH'];
$KommentarComma = $row['Versandkosten_Kommentar'];
$Kommentar = str_replace(",", "", $KommentarComma);
if ($i==1) {
$product = "Artikelnummer im Shop".","."EAN / GTIN / Barcodenummer / UPC".","."Herstellerartikelnummern (HAN/MPN)".","."Hersteller / Markenname".","."Produktname".","."Preis (Brutto)".","."Lieferzeit".","."Produktbeschreibung".","."ProduktURL".","."BildURL_1".","."Versandkosten".","."Vorkasse".","."Paydirekt".","."Paypal".","."Kreditkartenzahlung über BS PAYONE GmbH".","."Versandkosten Kommentar"."\n".$Artikelnummer.",".$pzn.",".$Herstellerartikelnummern.",".$brand.",".$name.",".$price.",".$Lieferzeit.",".$Produktbeschreibung.",".$url.",".$BildURL_1.",".$Versandkosten.",".$Vorkasse.",".$Paydirekt.",".$Paypal.",".$Kreditkartenzahlung.",".$Kommentar."\n";
} else {
$product = $Artikelnummer.",".$pzn.",".$Herstellerartikelnummern.",".$brand.",".$name.",".$price.",".$Lieferzeit.",".$Produktbeschreibung.",".$url.",".$BildURL_1.",".$Versandkosten.",".$Vorkasse.",".$Paydirekt.",".$Paypal.",".$Kreditkartenzahlung.",".$Kommentar."\n";
}
$i++;
fwrite($f, $product);
}
fclose($f);
?>
Try:
string utf8_decode ( string $data );
for example:
$ProduktbeschreibungComma = utf8_decode ($row['Produktbeschreibung']);
It should return the correct umlauts.
If it is in your csv file. Use utf_decode before output. Try to change the file_encoding of the csv file to utf8.

How do I omit the xml version tag when a xml file is created in php

I've made this program that updates an xml file based on entries in an array.
I've used FILE_APPEND because the entries are more than one and otherwise file gets overwritten. But the problem is the xml version tag prints out as many times as many entries are there.
So i want to remove this tag.
Here's my program:-
<?php
include 'array.php';
$xmlW = new XMLWriter();
$file = 'entry-'. date('M-D-Y') .'.xml';
/*$setting = new XMLWriterSettings();
$setting->OmitXmlDeclaration = true;*/
foreach($data as $d) {
if(in_array ($d['Mode'], array('ccAV','MB','Paypal','E2P'))) {
$recordType = 'receipt';
$xml_object = simplexml_load_file ('receipt.xml');
} else {
$xml_object = simplexml_load_file ('journal.xml');
$recordType = 'journal';
}
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")[0]->DATE = $d['InvoiceDate'];
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")[0]->NARRATION = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")[0]->EFFECTIVEDATE = $d['InvoiceDate'];
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[0]->LEDGERNAME = $d['Mode'];
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[0]->AMOUNT = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[1]->AMOUNT = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[2]->AMOUNT = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST/BANKALLOCATIONS.LIST")[0]->DATE = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST/BANKALLOCATIONS.LIST")[0]->INSTRUMENTDATE = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST/BANKALLOCATIONS.LIST")[0]->AMOUNT = 'Rahul';
$xml = $xml_object->asXML();
file_put_contents($file, $xml, FILE_APPEND);
}
?>
Thanks for the help.

Issues with creating dynamic INI files in PHP

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

Match & Replace a certain line of a text file

I am trying to setup a way where users can change the password to a certain area of a website they have access too and that password is stored as part of a .cfg text file. That is the file I need to pull it from. The contents of the file looks like this:
[main]
roomname = "Room Name"
topfile = /my/link/here
bannerfile = /my/link/here
bannersfile = /my/link/here
banner_freq = 40
bodyfile = /my/link/here
configfile = /my/link/here
actionfile = /my/link/here
memberfile = /my/link/here
moderatorfile = /my/link/here
logfile = /my/link/here
bootfile = /my/link/here
numusers = 30
password = mypassword
defaultmessage = "$USER$ : $SAYS$"
messagewrapper = '<TABLE WIDTH="100%" border=0 cellpadding=0 cellspacing=0><TR><TD>($DATESTAMP$ : $TIMESTAMP$) $PROVE$ $REGISTERED$ $MOD$ $MESSAGE$</TD></TR></TABLE><P>'
I have the change password form created, however what I am having trouble with is the .php file to process the form. I've been reading manuals but am not quite sure what else is missing or certain variables to use.
====
Edit/Update
I am updating my code below with my save.php form. It seems to be working except that its overwriting the entire file blankly and I'm not sure why its doing that. I'm also including my form coding from the send page.
<?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['password'];
$filevar = '/my/site/location/here/prpwtest/prtest.txt';
$fh = fopen($filevar, "w");
$file_contents = file_get_contents($filevar);
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$data.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
$success_page = '/my/site/location/here/pulldowns/savesuccessful.html';
header('Location: '.$success_page);
}
}
?>
And here is a snippet of my save code:
<form name="loginform" method="post" action="my/site/location/here/prpwtest/prpwtestsave.php">
<input name="password" type="password" /><p><input name="Submit" type="submit" /></form></p></center>
</div>
Give this a try:
$fileurl = '/path/to/my/file/here/file.cfg';
$replace = 'what I want to put in there when they submit';
$file = file($fileurl, FILE_IGNORE_NEW_LINES); // Get file as array of lines
foreach ($file as $n=>$line)
if (substr($line, 0, 8) === 'password') // Line starts with 'password'
$file[$n] = 'password = '.$replace; // Replace password line
file_put_contents($fileurl, implode("\n", $file)); // Put file back together
You need to parse data from $file_contents.
I.e. after reading of this string, you have to process it line by line to find string starting with 'password=' to modify it. You can use explode() for splitting of this string:
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$newpassword.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
}
Try this.
$array = parse_ini_file('your_ini_file.ini', 'main');
$array['main']['password'] = 'set your password here';
$str = '[main]'."\r\n";
foreach($array['main'] as $key => $value){
$str .= $key.' = '.$value."\r\n";
}
file_put_contents('test.ini', $str, LOCK_EX);

How to Create a CSV file using PHP (and upload it)

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

Categories