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);
Related
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
I'm a newbie in PHP and I'm trying to make a todo list that communicates with a .csv file,. So far I've managed to write a function that writes the user input into the csv file, but I'm stuck on writing a function that would parse (I'm not even sure if this is the correct term) every line of the .csv file into a multi dimensional array, so I could display every line of the list to my convenience in the PHTML file.
Here's what I have so far :
`<?php
//
// ─── DATA ────────────────────────────────────────────────────────────────────
//
$user_entry = array(
'title' => '',
'description' => '',
'date' => '',
'priority' => ''
);
// puts the data the users entered into an array
$user_entry['title'] = $_POST['title'];
$user_entry['description'] = $_POST['description'];
$user_entry['date'] = $_POST['date'];
$user_entry['priority'] = $_POST['priority'];
//
// ─── FUNCTIONS ──────────────────────────────────────────────────────────────────
//
function writeInList() {
//parses the $user_entry array into the .csv file
global $user_entry;
$file = fopen("todo.csv","a");
fputcsv($file, $user_entry, ",");
fclose($file);
}
function displayList() {
//That's where I'm stuck.
$file = fopen("todo.csv","r");
$fileCountable = file("todo.csv");
for ($i = 0; $i < count($fileCountable); $i++) {
$csvContent = fgetcsv($file, 1000, ",");
foreach ($csvContent as $value){
$var[$i] = $value;
}
echo '<br>';
}
fclose($file);
}
//
// ─── MAIN CODE ─────────────────────────────────────────────────────────────
//
writeInList();
include 'todolist.phtml';`
I'm sorry if it has been discussed before. I've searched a lot and found similar questions but can't get to make it work in my own code. Thanks a lot in advance if anyone takes the time to take a look at my code !
This is also my very first time posting here so I hope I'm doing it right.
You did pretty good. You can look at fgetcsv documentation for more. I would have change you function so it will get the argument as input (try avoid using global)
// insert data
function writeInList($user_entry, $path ) {
$file = fopen($path ,"a");
fputcsv($file, $user_entry, ",");
fclose($file);
}
//extract data
function getList($path, $limit = 100000) {
$file = fopen($path, "r");
if (!$file) return null; // or throw error or print to log
$allRows = []; //
while (($data = fgetcsv($file, $limit, ",")) !== FALSE) {
$allRows[] = $data; // as fgetcsv return array already exlode by ","
}
fclose($file);
return $allRows;
}
Now you have 2-Dim array return from getList. Use is as getList("todo.csv") and display as you pleased.
Hope that helps!
continue on PHP duplicate staffID
code
$data[0] = 0001,Ali,N,OK
$data[1] = 0002,Abu,N,OK
$data[2] = 0003,Ahmad,N,OK
$data[3] = 0004,Siti,Y,Not OK. Only one manager allowed!
$data[4] = 0005,Raju,Y, Not OK. Only one manager allowed!
I write it as following:
for($i = 0; $i < 5; $i++)
{
$data[i] = $staffID[$i].','.$staffname[$i].','.$ismanager[$i].','.$remark[$i];
}
Next I go to write csv file.
$file_format = "staffreport.csv";
$file = fopen($file_format,"w");
foreach($data as $line)
{
$replace = str_replace(",","|", $line);
fputcsv($file, array($replace));
echo $replace.'<br />';
}
fclose($file);
output (echo $replace)
0001|Ali|N|OK
0002|Abu|N|OK
0003|Ahmad|N|OK
0004|Raju|Y|Only one manager allowed!
0005|Siti|Y|Only one manager allowed!
In CSV file (staffreport.csv)
0001|Ali|N|OK
0002|Abu|N|OK
0003|Ahmad|N|OK
"0004|Siti|Y|Only one manager allowed!"
"0005|Raju|Y|Only one manager allowed!"
Why my csv file have double quote("")? How do I solve it?
change this bit like so.
for($i = 0; $i < 5; $i++)
{
$data[i] = array($staffID[$i],$staffname[$i],$ismanager[$i],$remark[$i]);
}
fputcsv wants an array of columns it will then insert the separators and quote marks as needed.
fputcsv usually uses commas for separators, if you want pipes: do this:
fputcsv($file, $line,'|');
why the quotes? probably because of the spaces.
if you must avoid the quotes,
fputcsv($file, $line,'|','');
hope that helps.
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);
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
}
}