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)
Related
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);
}
I'm trying to write in 2 differents columns in a csv file but everything I've found set all the values in the first column with a separator.
Here is a small modification of the script example on php.net
<?php
$list = array (
['City', 'Country'],
['Brussels', 'Belgium'],
['Paris', 'France'],
['Berlin', 'Germany']
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
And here is my csv file (I use Excel)
My question: is it possible to have the cities in A column and the countries in B column?
Thanks you for your help
You need to tell your spreadsheet program that the columns are separated by commas.
You will probably get the option to nominate a delimiter on opening the file.
I think you also have an option on a column - something like "Text to columns"
You can tell fputcsv() to use a different string as the delimiter instead of comma. This will use TAB, which is probably Excel's default:
fputcsv($fp, $fields, "\t");
<?php
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
print_r ($theData);
fclose($fh)
?>
This is my current code, which has successfully read my file and printed the data to the screen. However now when I try to explode the data I just get a sever error and the page doesn't load at all, the only error message I get is page may be down for maintenance or configured incorrectly and I don't understand why it isn't working.
I am trying to put
$my_array = explode("/n", $theData);
after the data has been read, and before it is printed, but every time I add it the page gives up, but when I take it out the page loads again fine.
I need to be able to put in a foreach loop to explode the data and print it out one line at a time (it's an email directory) but I don't understand why it's not working.
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array()
$my_array = explode("\n", $theData);
foreach($my_array as $line)
{
$tmp = explode(" ", $line);
$assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh)
$mail = $assoc_array;
I have tried this code, which I found while doing the original research for how to read from .txt file to array, but it still throws up the server error problem.
Could someone explain where I'm going wrong?
In the end the code I've used is:
<?php
// Open the file
$filename = 'pvemail.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
print_r ($array);
?>
I've managed to read the data and print each line out into an array, now all I need to do is make it look nice! Thanks a lot for your help guys!
Initial problems
Looks like you have a few missing semicolons, unless you typed the reference code by hand and your actual code is correct.
$assoc_array = array()
fclose($fh)
offset 1 does not exist
$tmp[1] does not exist, which means some $tmp either had no values or only one value. It is most likely the case that one of the lines is a single word without a space or completely empty.
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.
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);