merger the csv data with php? - php

There are many CSV file like the following:a.csv, b.csv, aab.csv etc.
They hold the same column and header. Now I want to put all the csv data into whole.csv. With only one header. How can I do it?
a.csv data:
header1 title post.....
test who posand
b.csv data:
header1 title post.....
head she pnow
etc .....
The whole.csv will contain all the csv data.
eg:
header1 title post.....
head she pnow
test who posand
I tried the following code.but not get I want to:
$csvs = glob("*.csv");
foreach($csvs as $csv) {
$row = 1;
if (($handle = fopen($csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$fp = fopen("whole.csv", 'w');
fputcsv($fp, $data);
$row++;
}
fclose($handle);
}
}
I have put all CSV files in the same directory.

For every input csv file you are opening the resultant csv file in write mode:
$fp = fopen("whole.csv", 'w');
which wipes the content of the whole.csv!!
You need to open the whole.csv file just once outside the loop and keep writing into it.
$csvs = glob("*.csv");
$fp = fopen("whole.csv", 'w');
foreach($csvs as $csv) {
$row = 1;
if (($handle = fopen($csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
fputcsv($fp, $data);
$row++;
}
fclose($handle);
}
}

Have a look at file_put_contents.
You would open each CSV file, then use file_put_contents passing whole.csv as the $filename parameter, the file handle as the $data parameter and use the FILE_APPEND flag to tell it to append the contents instead of overwriting.

Related

PHP - Convert Tab Delimited TXT file to CSV

I'm trying to convert a tab delimited .txt file into a .csv file.
I was able to use fgetcsv() to open the txt file and get the data for each line with the following code:
$handle = fopen("fileurl.com", "r");
$row = 1;
if (($handle = fopen("fileurl.com", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
print_r($data);
}
fclose($handle);
}
Now i just need to create a csv file from the data array. I've tried using fputcsv(), but haven't had any luck. I've tried something like this, but the csv file it creates isn't correct and only has 1 row:
$fp = fopen('file.csv', 'w');
fputcsv($fp, $data, "\t");
fclose($fp);
An example of how to create a .csv file from the $data array would be great. I've spent a lot of time researching and trying to get this figured out, but haven't been able to get it working.
fputcsv() only writes one line at a time. Not the whole file. You you need to loop through $data in order to add all of that data into your CSV file.
$fp = fopen('file.csv', 'w');
foreach ($data as $line) {
fputcsv($fp, $line);
}
fclose($fp);
A full example using your code:
$handle = fopen("fileurl.com", "r");
$lines = [];
if (($handle = fopen("fileurl.com", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
$lines[] = $data;
}
fclose($handle);
}
$fp = fopen('file.csv', 'w');
foreach ($lines as $line) {
fputcsv($fp, $line);
}
fclose($fp);
This is the correct way to write data into csv file
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
In fputcsv we use second parameter as an array .
along with it $attachment = mb_convert_encoding($attachment, 'UTF-8', $parts[$i]->parameters[0]->value); also needed for tsv to csv. it will change file type to text/plain

Converting TAB Delimited to CSV

I'm currently opening a TAB delimited file with the following code...
if (($handle = fopen($filetxt, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {
// var_dump($data);
$num = count($data);
echo "<br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Now I'm just trying to figure out how I can put the data into a CSV using fputcsv. An example would be great -- right now I'm just trying to get the headers into a CSV and then I can go from there.
The data right now (that's being echoed) looked like this...
part_number
aaia_part_term_id
short_description
bullet_points
list_price
jobber_price
base_price
epc_code
length
width
height
weight
image_name
If I could just figure out how to echo only the header into the CSV, I think I can figure out the rest.
fopen only gives you a handle to the file. A csv file's formatting relies going through each line, the way you are reading the file uses all contents at once, try:
<?PHP
if($handle = fopen($filetext, "r") !== FALSE){
while (!feof($handle)) {
$line_of_text = fgets($handle);
foreach( fgetcsv($line_of_text, 0, "\t") as $csv_item)
print $csv_item."," ;
print "<br>";
}
fclose($handle);
}
?>
I haven't tested this
Since a CSV file is just a comma delimited data file, it might be simpler just to read the current tab-delimited file line by line, and replace tabs with commas
if (($handle = #fopen($filetxt, "r")) !== false) {
while (($line = fgets($handle, 0)) !== false) {
$csv_line = str_replace("\t", ",", $line);
// write $csv_line to your csv file
}
fclose($handle);
}

merging multiple csv files using php

I want to create a command line php script which would merge/join multiple CSV files from a folder into one.
Each CSV file has 2 columns delimited by comma (,) but multiple number of rows varies. Also each of the CSV file name is unique so when we merge the CSV files I want the file name of the CSV to be the first column for each rows in the file.
So eventually when the script it run it’ll join multiple CSV files under a folder to one. From 2 columns the output file will have 3 columns where the first column would be the file name.
<?php
$nn = 0;
foreach (glob("*.csv") as $filename) {
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$c = count($data);
$csvarray[$nn][] = $filename;
for ($x=0;$x<$c;$x++)
{
$csvarray[$nn][] = $data[$x];
}
$nn++;
}
fclose($handle);
}
}
$fp = fopen('../file.csv', 'w');//output file set here
foreach ($csvarray as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
I didn't make any test on it though, here is the logic and code you can follow.

Skip first line of fgetcsv method

I have a CSV file and I read data from CSV file then I want to skip first line of CSV file.Which'll contain any header. I am using this code.
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
// Code to insert into database
}
When I insert data into th database then header should not to be saved into the database.
Before beginning the while loop, just get the first line and do nothing with it. This way the logic to test if it's the first line is not needed.
fgetcsv($file, 10000, ",");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
//....
}
try:
$flag = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
// rest of your code
}
A bit late, but here is another way to do so (without having to count all the lines): with fgets
$file = fopen($filename, 'r'); // create handler
fgets($file); // read one line for nothing (skip header)
while (($line = fgetcsv($file, 10000, ",")) !== FALSE) {
// do your thing
}
One might consider this to be more elegant
You can add a simple check and skip the query if the check fails:
$firstline = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
if (!$firstline) {
// Code to insert into database
}
$firstline = false;
}
Try this simple code.
$file = fopen('example.csv', 'r'); // Here example is a CSV name
$row = 1;
while (($line = fgetcsv($file, 10000, ",")) !== FALSE) {
// $line is an array of the csv elements
if($row == 1){ $row++; continue; } // continue is used for skip row 1
// print_r($line);
// rest of your code
}
You should use the fseek() method in order to get the desired line, regardless the current pointer position.
At this example, get the first line after the loop:
$file = fopen($path, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
// ...
}
fseek($file, 1, SEEK_CUR);
You can use the third parameter to position the pointer in the file, as is:
SEEK_SET – It moves file pointer position to the beginning of the file.
SEEK_CUR – It moves file pointer position to given location.
SEEK_END – It moves file pointer position to the end of file.

update one column record in a csv with php

there are two columns in my csv file,eg:
image gallery
/1.jpg /a.jpg;/b.jpg
..... .....
now i want to update the gallery content to /1.jpg;/a.jpg;/b.jpg. namely,add the content of image collumn and ; to the gallery content.
the following is my code.when i run it. it can't update the content of the csv.i am get stucked.
$dir = getcwd();
$files = scandir($dir);
foreach ($files as $file) {
$parts = pathinfo($file);
if ($parts['extension']!="csv") {
continue;
}
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
$data[1]=$data[0].";".$data[1];
fputcsv($file, $data);
}
fclose($handle);
}
open file in write or append mode and
fputcsv expects first parameter to be resource and you have given file path
which is causing problem
change it
fputcsv($handle, $data);
Please check the file permission first and after that you have to change the handle to both read and write and also please check whether the data[1] is having the values.
Because in Your code the the data[0] only will fetch the lines as a string which is separated with ";" so you have to explode it and after that do the operations.

Categories