PHP import CSV file and use data as variables - php

I would like to import a CSV document and parse its content to use it as variables. The document would always have fixed column names and column numbers. Any examples would be excellent.
I could only find a parse that shows the contents of the CSV file:
<?PHP
/**
* parse-csv.php
*/
$err_upTmpName = 'csvfiletutorial.csv';
$row = 0;
if (($handle = fopen($err_upTmpName, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($row == 0){
$row++;
} else {
// $data[0] = first name; $data[1] = last name; $data[2] = email; $data[3] = phone
if(!empty($data[0]) && !empty($data[1])) echo $data[0].' - '.$data[1].' - '.$data[2].' -
'.$data[3].' - '.$data[4].'<br/>';
}
}
} else {
echo 'File could not be opened.';
}
fclose($handle);
?>
Input sample csv:
date,value,value2
4.10.2019,15,10
Desired output csv:
using values from CSV file in a formula for example: 15+10
output=
date,sum_values
4.10.2019,25
output gets saved to a new CSV file

Related

Value's not visible when importing CSV after values are added by fputcsv with php

I'm trying to make a translation module for my web project and i hit a wall. I written two functions, one for importing the CSV data and the other for changing, deleting and adding new data to the CSV file.
Everything works like a charm except the adding part. It adds the data to the CSV file but when i want to import it in the website via PHP it doesn't display the added values. (It see that their should be values but it gives empty results in return) the function i use for reading the csv file is:
// Load in CSV (File name, delimiter, Fixed array[key,value] (optional))
function load__CSV($filename='', $delimiter=';', $fixed = null){
if(!file_exists($filename) || !is_readable($filename)) {
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 100000, $delimiter)) !== FALSE) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
if($fixed != null) {
foreach($data as $entry){
$set_csv[$entry[''.$fixed[0].'']] = $entry[''.$fixed[1].''];
}
} else {
$set_csv = $data;
}
return $set_csv;
}
The function i use to add, edit or remove CSV content is:
// Change csv
function update__csv($csv = 'csv/language.csv',$key = array(2,''),$values = array([3,''],[4,'']),$status = 'change') {
$input = fopen(BASE_URL.$csv, 'r');
$output = fopen(BASE_URL.'csv/temporary.csv', 'w');
while (false !== ($data = fgetcsv($input, 10000, ";"))) {
if ($data[$key[0]] == $key[1]) {
foreach ($values as $value) {
$data[$value[0]] = $value[1];
}
if ($status == 'change' || $status == 'new') {
fputcsv($output, $data, ";");
}
} else {
fputcsv($output, $data, ";");
}
}
if($status == 'new'){
fputcsv($output, $values, ";");
}
fclose( $input );
fclose( $output );
unlink(BASE_URL . $csv);
rename(BASE_URL . 'csv/temporary.csv', BASE_URL . $csv);
}
If i add new values to the CSV file and then open the CSV on my PC and safe it again (without changing a thing) to CSV with UTF-8 encoding then it works as expected and loads the correct data. If i open the CSV in Notepad++ i see this difference between manual added items and php added items:
I tried other encoding methods but that is kinda new for me so i think i did something wrong. Thank you in advance for helping me!
I did find the answer after some more debugging. One value of the array didn't contain a string but a true or false statement. This meant that it didn't add the data the right way into the CSV file.
I fixed it by adding strval() to every variable before putting it into an array.

Retrieve multiple lines within same cell from CSV file

I am trying to retrieve some data from CSV file. I used the following code to go through CSV:
//create array for csv file
$array_data = array();
$row = 0;
if (($handle = fopen("import/pdf_data.csv", "r")) !== FALSE) {
// read the CSV from root folder "web/interval/import"
while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {
if ($row > 0) {
$array_data[$row] = $data;
}
$row++;
}
fclose($handle);
}
//loop through all the feature data array
foreach ($array_data as $entry_value => $array_column) {
foreach( $array_column as $value )
{
//split data
list($col1,$col2,$col3) = explode( ',', $value );
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
When I print the columns... col1 and col2 are fine as they have only one single value in their cells. col3 may contain multiple lines. Let's say for example (see below one cell of col3):
col3
::::::::::::::
Text-a in line 1
Text-a in line 2
Text-a in line 3
If there are multiple lines within one cell then the CSV output will be like this:
"Text-a in line 1Text-a in line 2Text-a in line 3"
and with the code I use above it prints the first line
"Text-a in line 1
then in a new entry the second line etc etc.
What I want to achieve is the following format
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
Which doesn't work with multiple lines as I get this:
Name: Test, Surname: Test2, Text: "Text-a in line 1
Name: , Surname: , Text: Text-a in line 2
Any suggestions would be much appreciated, thank you
A CSV file may contain multi-line value in a cell. But it needs to be enclosed in quotes. Excel does this correctly - create a test file and save into CSV. PHP function fgetcsv also can read such files correctly.
Example file:
"col1","col2","col3"
"test1","test2.1
test2.2
test2.3","test3"
The second column in the second row contains multi-line value and this is a perfectly valid CSV file.
Here is the correct code:
$array_data = array();
$row = 0;
if (($handle = fopen("import/pdf_data.csv", "r")) !== FALSE) {
// read the CSV from root folder "web/interval/import"
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if ($row > 0) {
$array_data[$row] = $data;
}
$row++;
}
fclose($handle);
}
//loop through all the feature data array
foreach ($array_data as $row) {
list($col1,$col2,$col3) = $row;
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
}
I could advice you by another simple solution. It is using fgets() and explode()
$handle = fopen("inputfile.txt", "r");
$out = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
$arr = explode(',' $line);
$out[] = trim($arr[2]); // Supposing you want to get the third cell.
}
fclose($handle);
} else {
// error opening the file.
}
print_r($out);
Reference: How to read a file line by line in php

PHP use the fputcsv CSV to write same data in column for each row

I am trying to put a new data "exemple" for each line of the CSV. The lines of the csv varies. The header column name would be ExempleRow
There is not separator only a delimiter which is the semi colon.
I'm using fputcsv, it must have an array to fill the csv file with desired data. But in my case the number of lines changes for each csv.
So far it adds the new column with but I can't understand how to put the same value in each line for that column ?
<?php
$newCsvData = array(); // here should I specify the same data value "exemple data" for each line ? but how ?
if (($handle = fopen("exemple.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 9999, ";")) !== FALSE) {
$data[] = 'ExempleRow';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('exemple.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line,';',' ');
}
fclose($handle);
?>
If you want to show the keys of the array as the first column then you can do this. If you dont have an associative array or you want to hard code the column headers for what ever reason you can simply change the array_keys($line) for a hard coded array.
$handle = fopen('exemple.csv', 'w');
$keys = false;
foreach ($newCsvData as $line) {
if ($keys === false) {
//$header = array('HeaderOne', 'HeaderTwo', 'HeaderThree', 'HeaderFour'); Use this if you want to hard code your headers
fputcsv($handle, array_keys($line), ';', '');
$keys = true;
}
fputcsv($handle, $line,';',' ');
}
fclose($handle);

Importing csv into mysql (List of Codes)

So I have a list of codes (100,000) to be exact and I got them delivered in a csv file.
I want to put theses codes in a database so I can later get them using my php script.
However my question is how do I get my codes from the file in the right table?
This is what my database looks like at the moment.
The codes from the file need to be inserted in table code.
Hope someone can help me out with this one.
You probably will find this helpful (pls adjust the table and others names):
LOAD DATA INFILE 'codes.csv'
INTO TABLE codes
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
(#id,code,#active)
SET id = null;
SET active = '1'
More details:
http://www.mysqltutorial.org/import-csv-file-mysql-table/
Try this:
you can upload your csv file and post it. then use this function.
this is the PHP code:
function get_csv_file($filename){
if (($handle = fopen($filename, "r")) !== false) {
$filesize = filesize($filename);
$firstRow = true;
$aData = array();
while (($data = fgetcsv($handle, $filesize, ";")) !== false) {
if($firstRow) {
$aData = $data;
$firstRow = false;
} else {
for($i = 0;$i < count($data); $i++) { //only for csv file
if($data[$i] != '')
$aData[] = $data[$i];
}
}
}
//print_r($aData);
fclose($handle);
$finalscrap = array_unique($aData);
// echo "<pre>";
// print_r($finalscrap);
// echo "<pre/>";
return $finalscrap; //this is your record as array format
}
}

nokia csv file import issue in php

Title,"First name","Middle name","Last name","address"
Mr.,"prince","M","Kachhadiya","A-42,AdarshNagar-2
 c.g Road,
"
Address field have value like "A-42,AdarshNagar-2
 ChhpraBhatha Road," this value have comma(,) in between and csv file default field separator is comma(,) so it will assume A-42 and AdarshNagar-2
 c.g Road as different field value.
how can i resolve it?
My Php Code:
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
// Code for parse csv data
}
use fgetcsv() to read from a file . Refer http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
Title,"First name","Middle name","Last name","address"
Mr.,"prince","M","Kachhadiya","A-42,AdarshNagar-2 c.g Road,"
//You can't split the strings using CSV functions so better do some manual work
//All csv values are quoted with double quotes so split the string like this
//**If file size is minimum use this function**
$data = file_get_contents('<file_path>');
$parsed_string = explode('",', $data);
$cnt = count($parsed_string);
for($i=0; $i<$cnt; $i++)
{
$value = substr($parsed_string,1);
}
//**If file size is maximum use this**
$file = fopen("<file path>","r");
while(! feof($file))
{
$data = fgets($file);
$parsed_string = explode('",', $data);
$cnt = count($parsed_string);
for($i=0; $i<$cnt; $i++)
{
$value = substr($parsed_string,1);
}
}
fclose($file);

Categories