fgetcsv to fetch data within double quotes - php

I am trying to upload csv file data using PHP,
CSV File Data (Semicolon separated)
Name;Nom;Tel;Email;Ville;ID
x;DURAND;11;aprasquier+testvia#odm-tech.com;"Paris";1
PHP Code:
$handle = fopen('test.csv', "r");
while (($data = fgetcsv($handle,0, ";")) !== FALSE)
echo var_dump($data);
output:
array(1) {
[0]=> string(53) "x;DURAND;11;aprasquier+testvia#odm-tech.com;"Paris";1"
}
Expected output is ,
array(6) {
[0]=> string(1) "x"
[1]=> string(6) "DURAND"
[2]=> string(2) "11"
[3]=> string(31) "aprasquier+testvia#odm-tech.com"
[4]=> string(5) "Paris"
[5]=> string(1) "1"
}
Please anyone advise on this asap.

Related

import csv with php to mysql

I'm importing a csv file into a mysql table with php.
Now I'm going to put some lines as I have in the csv. csv has no header.
I leave the script of how I created the table in mysql:
CREATE TABLE `Areceber` (
`Id` int NOT NULL AUTO_INCREMENT,
`N_utente` varchar(45) DEFAULT NULL,
`Ano` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
now I will put the html script:
<form method="post" action="conexaoexcel1.php" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" name="submit_file" value="Submit"/>
</form>
and now the page conexaoexcel1.php:
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ";")) !== false)
{
foreach ($csv as $key => $value){
$Id = str_getcsv($value[0], ',');
var_dump($Id);
}
}
Now when I var_dump the first column it returns like this:
array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "2" } array(1) { [0]=> string(1) "3" } array(1) { [0]=> string(1) "4" } array(1) { [0]=> string(1) "5" } array(1) { [0]=> string(1) "6" } array(1) { [0]=> string(1) "7" } array(1) { [0]=> string(1) "8" } array(1) { [0]=> string(1) "9" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "2" }
Up to the line that has the number nine it returns fine, but when it starts on the line that has the number 10, it only returns the number 1 without the zero and so on. Can you help solve the problem?
Your $csv is already an array of data, and to output first column, use $csv[0] without looping.
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ";")) !== false)
{
$Id = $csv[0];
var_dump($Id);
}
Just check if your delimiter is right. If it's comma delimited change line
while(($csv = fgetcsv($file_open, 1000, ";")) !== false)
to
while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
Otherwise it should work.

When trying to export this array as a CSV file in php I get an empty sheet

I have this array, and I want to convert it into a CSV file, the problem, is that the array does not generate a csv properly, but just empty fields, why?
Here's my array contents (the array that I'm printing here is $listaParaCSV, as the code shown below):
array(2) {
[0]=>
array(22) {
[0]=> string(6) "nombre"
[1]=> string(14) "Lun 11-01-2021"
[2]=> string(14) "Mie 13-01-2021"
[3]=> string(14) "Lun 18-01-2021"
[4]=> string(14) "Mie 20-01-2021"
[5]=> string(14) "Lun 25-01-2021"
}
[1]=>
array(85) {
["Pedro"]=>
array(21) {
["Lun 11-01-2021"]=> string(2) "SI"
["Mie 13-01-2021"]=> string(2) "SI"
["Lun 18-01-2021"]=> string(2) "SI"
["Mie 20-01-2021"]=> string(0) ""
["Lun 25-01-2021"]=> string(0) ""
}
["Maria"]=>
array(21) {
["Lun 11-01-2021"]=> string(2) "SI"
["Mie 13-01-2021"]=> string(2) "SI"
["Lun 18-01-2021"]=> string(0) ""
["Mie 20-01-2021"]=> string(0) ""
["Lun 25-01-2021"]=> string(0) ""
}
}
}
And here is my code (the variables $listaFechas and $paraCSV are arrays themselves):
$listaParaCSV = array (
$listaFechas,
$paraCSV
);
$fp = fopen('backupAsistenciaCurso-'.$cursoID.'.csv', 'w');
foreach ($listaParaCSV as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The expected result is a CSV file that when opened with open with OpenCalc or excel shows something like this:
The problem is that you are looping over the $listaParaCSV with has 2 elements, the headers and then all the data in one element.
Instead, if you write out the headers and then loop over $paraCSV, adding the key (the name) as the first field before outputting them...
$fp = fopen('backupAsistenciaCurso-'.$cursoID.'.csv', 'w');
fputcsv($fp, $listaFechas);
foreach ($paraCSV as $key => $fields) {
array_unshift($fields, $key);
fputcsv($fp, $fields);
}

PHP unordered associative array to CSV line matching headers to keys, creating new headers as needed

I have a series of arrays, like similar:
$my_array = {"foo"=>"bar", "sudo"=>"make_sandwhich", "bam"=>"bang"};
and a csv like:
Header 1, Header 2, foo, Header 4 , bam , Header 5
Lorem. , Ipsum. , , cheesecake, Henrietta, Loreal
, , , , , New Hampshire
And I want the csv to look like this when I add the example line from the start...
Header 1, Header 2, foo, Header 4 , bam , Header 5 , sudo
Lorem. , Ipsum. , , cheesecake, Henrietta, Loreal ,
, , , , , New Hampshire,
, , bar, , bang , , make_sandwhich
I've tried messing with the fputcsv, but it doesn't seem to have anything near the functionality I need. Is there a way to do this?
It can be achieved with fgetcsv and fputcsv and "some" additional processing.
Read your csv file (first row are the headers), then add the new headers from your input row.
Then read the rows, create missing data for new headers and add a new row with all the headers at the end.
Then just write that data back to csv file.
a.csv - input:
Header 1, Header 2, foo, Header 4 , bam , Header 5
Lorem. , Ipsum. , , cheesecake, Henrietta, Loreal
, , , , , New Hampshire
code:
<?php
$myArray = ["foo"=>"bar", "sudo"=>"make_sandwhich", "bam"=>"bang"];
$readHandle = fopen("a.csv", "r");
// get headers (first row)
$headers = fgetcsv($readHandle);
$allHeaders = [];
foreach ($headers as $header) {
$allHeaders[] = trim($header);
}
// add missing headers from the input data (so to headers from file add sudo header)
foreach (array_keys($myArray) as $data) {
if (!in_array($data, $allHeaders)) {
$allHeaders[] = $data;
}
}
var_dump($allHeaders);
// read all rows from the file and add the new headers
$rows = [];
while($row = fgetcsv($readHandle)) {
foreach ($allHeaders as $k => $header) {
$row[$k] = isset($row[$k]) ? trim($row[$k]) : '';
}
$rows[] = $row;
}
// add the new row from input data
$newRow = [];
foreach ($allHeaders as $header) {
$newRow[] = $myArray[$header] ?? '';
}
$rows[] = $newRow;
var_dump($rows);
fclose($readHandle);
// now write headers and rows to csv file
$writeHandle = fopen('b.csv', 'w+');
fputcsv($writeHandle, $allHeaders);
foreach ($rows as $row) {
fputcsv($writeHandle, $row);
}
fclose($writeHandle);
$allHeaders:
array(7) {
[0]=>
string(8) "Header 1"
[1]=>
string(8) "Header 2"
[2]=>
string(3) "foo"
[3]=>
string(8) "Header 4"
[4]=>
string(3) "bam"
[5]=>
string(8) "Header 5"
[6]=>
string(4) "sudo"
}
$rows:
array(3) {
[0]=>
array(7) {
[0]=>
string(6) "Lorem."
[1]=>
string(6) "Ipsum."
[2]=>
string(0) ""
[3]=>
string(10) "cheesecake"
[4]=>
string(9) "Henrietta"
[5]=>
string(6) "Loreal"
[6]=>
string(0) ""
}
[1]=>
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
[5]=>
string(13) "New Hampshire"
[6]=>
string(0) ""
}
[2]=>
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(3) "bar"
[3]=>
string(0) ""
[4]=>
string(4) "bang"
[5]=>
string(0) ""
[6]=>
string(14) "make_sandwhich"
}
}
b.csv - output:
"Header 1","Header 2",foo,"Header 4",bam,"Header 5",sudo
Lorem.,Ipsum.,,cheesecake,Henrietta,Loreal,
,,,,,"New Hampshire",
,,bar,,bang,,make_sandwhich
I hope you dont want the spaces in csv for formatting. It can also be done but you need to keep the amount of characters for the longest string in each column and pad the values to that lengths.

Merge Two csv files with php

i have two csv files: one contracts data and the other containing awarded contracts. I need to combine these two files using common field(contractname) and compute total amount of current awarded contracts.
Link to csv files:
https://github.com/younginnovations/problem-statements/tree/master/clean-up-contracts-data
I do get desired output bt undefined offset error comes up.
the code:unset(awards_info[$y][0]); does unsets the data but 'Undefined offset: 0' error occurs..
similarly the code $list_data[10]!=NULL also shows the same error
but both are producing desired output.
var_dump($awards_info):: produces following:
array(5) { [0]=> array(6) { [0]=> string(12) "contractName" [1]=> string(12) "contractDate" [2]=> string(14) "completionDate" [3]=> string(7) "awardee" [4]=> string(15) "awardeeLocation" [5]=> string(6) "Amount" } [1]=> array(6) { [0]=> string(15) "Contract-2070-3" [1]=> string(8) "5/9/2014" [2]=> string(9) "8/25/2014" [3]=> string(11) "SK Builders" [4]=> string(5) "Banke" [5]=> string(6) "200000" } [2]=> array(6) { [0]=> string(15) "Contract-2070-5" [1]=> string(9) "3/18/2014" [2]=> string(8) "4/8/2014" [3]=> string(24) "S engineering industries" [4]=> string(9) "Makwanpur" [5]=> string(6) "300000" } [3]=> array(6) { [0]=> string(15) "Contract-2070-9" [1]=> string(8) "3/6/2014" [2]=> string(8) "4/6/2014" [3]=> string(24) "Gourishankar nirman sewa" [4]=> string(8) "Lalitpur" [5]=> string(6) "400000" } [4]=> array(6) { [0]=> string(16) "Contract-2070-10" [1]=> string(8) "2/6/2014" [2]=> string(9) "6/16/2014" [3]=> string(11) "SK Builders" [4]=> string(5) "Banke" [5]=> string(6) "400000" } }
$file_contract=fopen('contracts.csv','r');
$file_awards=fopen('awards.csv','r');
while(($data=fgetcsv($file_contract))!=FALSE){
$contracts_info[]=$data;
}
while(($data=fgetcsv($file_awards))!=FALSE){
$awards_info[]=$data;
}
$con_count=count($contracts_info);
for($x=0;$x<$con_count;$x++){
if($x==0){
unset($awards_info[0][0]);
$data[$x]=array_merge($contracts_info[0],$awards_info[0]);
}
else{
$check=0;
$award_count=count($awards_info);
for($y=1;$y<$award_count;$y++){
if($awards_info[$y][0]==$contracts_info[$x][0]){
unset($awards_info[$y][0]);
$data[$x]=array_merge($contracts_info[$x],$awards_info[$y]);
$check=1;
}
}
if($check==0){
$data[$x]=$contracts_info[$x];
}
}
}
$final_data=fopen('final.csv','w');
foreach($data as $list_data){
fputcsv($final_data,$list_data);
}
fclose($final_data);
$c=0;
foreach ($data as $list_data){
if(($list_data[1]=='Current') && ($list_data[10]!=NULL))
{
$c+=$list_data[12];
}
}
echo $c;
You can just add the content file in the new file, without parsing files :
$fp = fopen('final.csv','w');
fwrite($fp, file_get_contents('contracts.csv'));
fwrite($fp, file_get_contents('awards.csv'));
fclose($fp);
echo file_get_contents('final.csv');
ok it's a wrong way. So i try to rewrite the loop :
for($x=0; $x < count($contracts_info); $x++) {
$data[$x] = $contracts_info[$x];
if($x == 0) {
if(isset($awards_info[$x])) {
$data[$x] = array_merge($data[$x], $awards_info[$x]);
unset($awards_info[$x]);
}
} else {
foreach($awards_info as $y => $award_info_datas) {
if($award_info_datas[0] == $contracts_info[$x][0]) {
$data[$x] = array_merge($data[$x], $award_info_datas);
unset($awards_info[$y]);
break;
}
}
}
}

Read Line From Text File

I have been given a textfile which contains data on time sheet. That line contains a name and a department and their time out/in.The code below allows me to display the entire textfile but I want to read in the values by name and department from file and want to display that .
<?php
$file = fopen("C:\Bhrugisha mam.txt","r") or exit("Unable to open file!");
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
this is some data from my text file...
VCANTECH - Log Report
6 Bhrugisha Shah
Hr
Department: HR
August, 2011 Page 1 of 2
-----------------------------------------------------------------------------------------------------------------
Date : 01/Aug/2011 Shift : 1 ( 9:30:00 AM To 6:30:00 PM )
LOG TIME : 9:23:00 AM LOG TYPE : IN
LOG TIME : 1:55:00 PM LOG TYPE : OUT
LOG TIME : 2:18:00 PM LOG TYPE : IN
LOG TIME : 6:45:00 PM LOG TYPE : OUT
This should get you there
$input = fread( $file, filesize("PATHTOFILE"));
preg_match("%Department:[\s]{1,}[a-z]{1,}%i", $input, $department);
var_dump($department);
//OUTPUT array(1) { [0]=> array(1) { [0]=> string(22) "Department: HR" }
preg_match_all("%log time : [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} (AM|PM) LOG TYPE : (IN|OUT)%i", $input, $matches);
var_dump($matches);
/*
OUTPUT
array(3) { [0]=> array(4) { [0]=> string(57) "LOG TIME : 9:23:00 AM LOG TYPE : IN" [1]=> string(58) "LOG TIME : 1:55:00 PM LOG TYPE : OUT" [2]=> string(57) "LOG TIME : 2:18:00 PM LOG TYPE : IN" [3]=> string(58) "LOG TIME : 6:45:00 PM LOG TYPE : OUT" } [1]=> array(4) { [0]=> string(2) "AM" [1]=> string(2) "PM" [2]=> string(2) "PM" [3]=> string(2) "PM" } [2]=> array(4) { [0]=> string(2) "IN" [1]=> string(3) "OUT" [2]=> string(2) "IN" [3]=> string(3) "OUT" } }
*/
foreach($matches[0] as $row){
preg_match("%[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} (AM|PM)%", $row, $logTime);
//var_dump($logTime);
//OUTPUT array(2) { [0]=> string(10) "9:23:00 AM" [1]=> string(2) "AM" } array(2) { [0]=> string(10) "1:55:00 PM" [1]=> string(2) "PM" } array(2) { [0]=> string(10) "2:18:00 PM" [1]=> string(2) "PM" } array(2) { [0]=> string(10) "6:45:00 PM" [1]=> string(2) "PM" }
$logTime = $logTime[0];
preg_match("%(IN|OUT)%",$row, $inOut);
var_dump($inOut);
//OUTPUT array(2) { [0]=> string(2) "IN" [1]=> string(2) "IN" } array(2) { [0]=> string(3) "OUT" [1]=> string(3) "OUT" } array(2) { [0]=> string(2) "IN" [1]=> string(2) "IN" } array(2) { [0]=> string(3) "OUT" [1]=> string(3) "OUT" }
$inOut = $inOut[0];
}
I would recommend making some edits to the regex's, as I just copy and pasted the spaces. [\s]{1,} can be used in place of the crazy spaces :P
You can use
$file = file('filename.txt');
It will return the array with each element containing each line.

Categories