Write to a CSV file on two columns - php

I am trying to create a CSV file. I have done this. I have put the below in a loop with the first and last lines outside of the loop.
$FileHandle = fopen('tech.csv', 'a+') or die("can't open file");
$stringa = $item." , ".$item2."\r\n";
fwrite($FileHandle, $stringa);
fclose($FileHandle);
However, it comes out like this in the CSV file:
a
b
c
d
Rather than the way I want it:
a b
c d
Basically, two columns rather than one.
What am I doing wrong?

Do you read those values from a file/stream using fgets()? Then the trailing linebreak is part of the string. Use trim() to remove the linebreak.
You might also be interested in the function fputcsv().

I really hope you don't open and close the file in every iteration as that puts a real strain on the filesystem. Instead, you could do something like this:
$csv = array();
foreach($myData as $row) {
$csv[] = trim($row['item1']).','.trim($row['item2']);
}
file_put_contents('tech.csv', implode("\r\n", $csv), FILE_APPEND);
Or, you could use the fputcsv function:
$fp = fopen('tech.csv', 'a+');
foreach($myData as $row) {
fputcsv($fp, array(trim($row['item1']), trim($row['item2']));
}
fclose($fp);

Related

How to change all values in a column of a csv file to a specific value php

I have a csv file that looks something like this (there are many more rows):
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
What I want to do is to change all the values in the fourth column,456,343 to 500.
I'm new to php and am not sure how to do this.
I have tried
<?php
$file = fopen('myfile.csv', 'r+');
$toBoot = array();
while ($data = fgetcsv($file)) {
echo $data[3];
$data[3] = str_replace($data[3],'500');
array_push($toBoot, $data);
}
//print_r($toBoot);
echo $toBoot[0][3];
fputcsv($file, $toBoot);
fclose($file)
?>
But it prints
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
Array,Array
not
Jim,jim#email.com,8882,500
Bob,bob#email.com,8882,500
I've looked at this post, PHP replace data only in one column of csv but it doesn't seem to work.
Any help appreciated. Thanks
You can use preg_replace and replace all values at once and not loop each line of the CSV file.
Two lines of code is all that is needed.
$csv = file_get_contents($path);
file_put_contents($path, preg_replace("/(.*),\d+/", "$1,500", $csv));
Where $path is the path and to the CSV file.
You can see it in action here: https://3v4l.org/Mc3Pm
A quick and dirty way to way to solve your problem would be:
foreach (file("old_file.csv") as $line)
{
$new_line = preg_replace('/^(.*),[\d]+/', "$1,500", $line);
file_put_contents("new_file.csv", $new_line, FILE_APPEND);
}
To change one field of the CSV, just assign to that array element, you don't need to use any kind of replace function.
$data[3] = "500";
fputcsv() is used to write one line to a CSV file, not the entire file at once. You need to call it in a loop. You also need to go back to the beginning of the file and remove the old contents.
fseek($file, 0);
ftruncate($file, 0);
foreach ($toBoot as $row) {
fputcsv($file, $row);
}

Create csv file from mysql results with php?

So I'm trying to make a .csv file which after I will download it,but the problem is that the rows are not going aranging properly.
I am using fputcsv.
$tot.="$codcomanda,$clientnume,$brandnume,$numeprod,$um,$cantitate,$updatare";
$list =array(
array('Comanda','Client','Categorie','Produs','UM','Cantitate','Actualizare'),
array($tot),
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The variable $tot is from a while statement and it gets its variable from different queries and I cannot find a php code on the internet that is for my needs.I've tried several ways to try and make it work but nothing.
I've tried making $tot different ways but none work,either it $tot.=
The csv file should have something like.
Title line,
Line 1,
Line 2,
etc
But my csv shows like
Title line,
"Line1,Line2,etc"
I've tried making $tot different ways but none work,either the csv show like this or doesn't display no content at all.
Solved: Using fwrite i've solved it.
$tot.="$codcomanda;$clientnume;$brandnume;$numeprod;$um;$cantitate;$updatare;\n";
$tot2="Comanda;Client;Brand;Produse;U.M;Cantitate;Actualizare;\n$tot";
$file = fopen("file.csv","w");
fwrite($file,$tot2);
fclose($file);
And it write's it like it should.
Try like the following example
<?php
$list =array(
array('Comanda','Client','Categorie','Produs','UM','Cantitate','Actualizare'),
array('P1','C1','CL1','2','2','Ct1','A1'),
array('P2','C2','CL2','2','2','Ct2','A2'),
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp)
?>
Try to add this line before the calling of fopen(): ini_set("auto_detect_line_endings", true)

How to overwrite a particular line in flat file?

My text file contains:
a
b
c
d
e
I can't figure out how to amend my code so that I can overwrite line 3 ONLY (ie replacing "c") with whatever I type into the input box 'data'. My code is as follows, currently the contents of the input box 'data' replaces my file entirely:
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "w") or die("Couldn't open $file for writing");
fwrite($fp, $data) or die("Couldn't write values to file");
fclose($fp);
I have it working the other way around, ie the code below reads line 3 ONLY into the text box when the page first loads:
$file = "data.txt";
$lines = file( $file );
echo stripslashes($lines[2]);
Can anybody advise the code I need to use to achieve this?
The only way is to read the whole file, change the 3rd line, then write it all back out. Basically, like so:
$lines = file($file);
$lines[2] = $_POST['data'];
file_put_contents($file, implode("\n", $lines));
Btw, your reading code does not "ONLY" read line 3 - it reads all lines as per file() and then you only use line 3.

Separating txt file to many csv files with PHP

So I was able to parse the txt file into a csv file
$data = array();
while ($line= fgets ($fh)) {
$stack = array($LAUS,$FIPS,$CountyName,$Date,$_CLF,$_EMP,$_UNEMP,$RATE);
array_push($data, $stack);
}
$file = fopen('file.csv','w');
foreach ($data as $fields) {
fputcsv($file, $fields,',','"');
}
fclose($file);
My question is, what is the best way to create multiple csv files that are seperated by Month (also the year, like Jan01.csv, Jan02.csv).
I'm taking a bit of a guess at the formatting of your date
while ($line = fgets ($fh)) {
// Not sure where you're getting these values, but I'm assuming it's correct
$stack = array($LAUS,$FIPS,$CountyName,$Date,$_CLF,$_EMP,$_UNEMP,$RATE);
// Assuming $Date looks like this '2011-10-04 15:00:00'
$filename = date('My', strtotime($Date)) . '.csv';
$file = fopen($filename,'a+');
fputcsv($file, $stack,',','"');
fclose($file);
}
This will be a little slow since you're opening and closing files constantly, but since I don't know the size of your original data set I don't want to use up all the memory caching the result before I write it.
Be aware that running this multiple times will end up with duplicate data being inserted into your CSV files. You may want to add some code to remove/clear out any currently existing CSV files before you run this bit of code.

How to concatenate two strings using fgetcsv and fputcsv?

I'm creating a script that will read a csv file and display it on a textarea using fgetcsv.
$handle = #fopen($filePath, "r");
if ($handle)
{
while (($buffer = fgetcsv($handle, 1000,",")) !== false)
{
foreach($buffer as $buff){
echo $buff."\n";
}
}
}
The format of the csv is
"line1-content1","line1-content2"
"line2-content1","line2-content2"
Using fgetcsv, the content will display inside the textarea without double-quote and comma. Can I format it so that it will also display the duoble quotes and comma?
Then upon saving it using fputcsv
$file_to_load = $_GET['filepath'];
$filePath = $dir.$file_to_load;
$trans = trim($_POST['txtarea']);
$keyarr = split("\n",$trans);
$fp = fopen($filePath, 'w');
foreach (array ($keyarr) as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Looking on the csv file, it saved the csv but displays it like this
"line1-content1
","line1-content2
","line2-content1
","line2-content2"
It separates the "line1-content1" and "line1-content2" into two lines and put a comma after the end of every line.
Now I want to keep the formatting of #2. How will I code it?
Can you guide me into the right direction? Thanks!
Sounds like you want to display the actual raw CSV text, not the parsed data within the CSV. Instead of using fgetcsv(), just use fgets() and you'll get the text line without any parsing, preserving the quotes and commas.
As for fputcsv, it's going to write out what you pass into it, so make sure that whatever's coming back from the form is cleaned up (e.g. extra line breaks stripped out).

Categories