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.
Related
I would like my CDATA section display the result of a function that generates a text from an sql query.
Create sql query and call function createXMLfile:
$statement = $connection->query("SELECT * FROM events ORDER BY ID DESC LIMIT 1");
$statement->execute();
$eventArray = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
array_push($eventArray, $row);
}
createXMLfile($eventArray);
Function that generate text from my sql query:
<?php
function write_records($eventArray) {
for($i=0; $i<count($eventArray); $i++){
$name = $eventArray[$i]['event_name'];
$city = $eventArray[$i]['event_city'];
?>A new event <?php echo $eventArray[$i]['event_name'];?> is coming in <?php $eventArray[$i]['event_city'];?>.<?php
}
return $eventArray;
}
?>
Function that create XML file (i use implode for convert array to a string):
function createXMLfile($eventArray){
$filePath = 'event.xml';
$content = implode(' ', write_records($eventArray));
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('INCIDENTS');
for($i=0; $i<count($eventArray); $i++){
$eventName = $eventArray[$i]['event_name'];
$eventCity = $eventArray[$i]['event_city'];
$eventXml = $dom->createElement('INCIDENT');
$name = $dom->createElement('EVENT', $eventName);
$eventXml->appendChild($name);
$city = $dom->createElement('CITY', $eventCity);
$eventXml->appendChild($city);
$eventXml->appendChild(new DOMElement('COMMENTAIRE'))->appendChild(new DOMCdataSection($content));
$root->appendChild($eventXml);
}
$dom->appendChild($root);
$dom->save($filePath);
}
XML file is generated but CDATA section display only this :
<![CDATA[Array]]>
Please can you tell me what's wrong ? Thanks for your help.
EDIT:
function createXMLfile($eventArray){
$filePath = 'event.xml';
$content = implode(' ', write_records($eventArray[0]));
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('INCIDENTS');
for($i=0; $i<count($eventArray); $i++){
$eventName = $eventArray[$i]['event_name'];
$eventCity = $eventArray[$i]['event_city'];
$eventXml = $dom->createElement('INCIDENT');
$name = $dom->createElement('EVENT', $eventName);
$eventXml->appendChild($name);
$city = $dom->createElement('CITY', $eventCity);
$eventXml->appendChild($city);
$eventXml->appendChild(new DOMElement('COMMENTAIRE'))->appendChild(new DOMCdataSection($content));
$root->appendChild($eventXml);
}
$dom->appendChild($root);
$dom->save($filePath);
}
Now sql values are displayed in CDATA section but not the generated text from function write_records($eventArray).
<![CDATA[concert Miami]]>
And i would like :
<![CDATA[A new concert is coming in Miami]]>
print_r($eventArray); give me same result :
$statement = $connection->query("SELECT * FROM events ORDER BY ID DESC LIMIT 1");
$statement->execute();
$eventArray = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
array_push($eventArray, $row);
}
print_r($eventArray);
createXMLfile($eventArray);
Apache Log say PHP Notice: Undefined offset :0 from variables values in function write_records($eventArray)
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'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.
My JSON result http://daysof.me/lowyat/list.php
What I did:
$num = 0;
$array = array();
foreach($rows as $go){
if($num == count($rows)-1){break;}
$reply = $go->find('td',3)->plaintext;//replies
$starter = $go->find('td',4)->plaintext;//starter
$views = $go->find('td',5)->plaintext;//views
$action = $go->find('td',6)->plaintext;//last action
$desc = $go->find('td',2)->find('div div',2)->plaintext;//description
$title = $go->find('td',2)->find('div div a',0)->plaintext;//topic name
$link = $go->find('td',2)->find('div div a',0)->href;
$array[]= array(
'title'=>$title,
'desc'=>$desc,
'starter'=>trim($starter),
'replies'=>trim($reply),
'url'=>'https://forum.lowyat.net'.$link
);
$num ++;
}
echo json_encode($array);
You'll see some single quote been turned into " and ampersand gave strange code.
How can I escape that? I tried 'title'=>htmlentities($title) still no luck with that.
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