I got a string with semi clones. I want to create a csv file.
$fp = fopen("abc.csv", "w");
$str = "FRUIT; STOCKS; TYPE\n lychee; B-type,A-type; instocks\n strawberry; A-type;N/A\n";
$rows = str_getcsv($str, PHP_EOL);
foreach($rows as $row) {
$data = str_getcsv($row);
fputcsv($fp, explode(';',$data), ";");
}
The fputcsv() doesn't seem to work correctly.
When I open the csv using EXCEL the data should be in separate columns where the semi colon (;) was.
FRUIT TYPE STOCKS
Lychee B-type,A-type instocks
Strawberry A-type N/A
EDIT:
My current output and problems are
1. If there's are more than one words those are wrapped by a " (e.g. below)
FRUIT;STOCKS;TYPE;"COST PER ITEM"
The final output is as (when opened in excel).
FRUIT;STOCKS;TYPE;"COST PER ITEM"
Lychee "B-type A-type"; instocks; $54;
Strawberry; A-type; N/A; $31;
Each ; is in a seperate column. I want the final output to be like this
FRUIT TYPE STOCKS COST PER ITEM
Lychee B-type,A-type instocks $54
Strawberry A-type N/A $31
Don't try to use str_getcsv() to parse the whole string into lines, str_getcsv() is designed to parse a single row, not the entire content of a file/string
$str = "FRUIT; STOCKS; TYPE\n lychee; B-type,A-type; instocks\n strawberry; A-type;N/A\n";
$rows = explode("\n", $str);
foreach($rows as $row) {
$data = str_getcsv($row, ';');
$data = array_map('trim', $data);
fputcsv($fp, $data, ';');
}
EDIT
It looks as though your MS Excel may be expecting a comma (,) as separator rather than a semi-colon (;).... so you may need to tell MS Excel this
explicitly write a sep=; line as the first line of your file
fwrite($fp, 'sep=;'.PHP_EOL);
before your data loop
Related
My text file sample.txt. I want to exclude the first row from the text file and store the other rows into mysql database.
ID Name EMail
1 Siva xyz#gmail.com
2 vinoth xxx#gmail.com
3 ashwin yyy#gmail.com
Now I want to read this data from the text file except the first row(ID,name,email) and store into the MYsql db.Because already I have created a filed in database with the same name.
I have tried
$handle = #fopen($filename, "r"); //read line one by one
while (!feof($handle)) // Loop till end of file.
{
$buffer = fgets($handle, 4096); // Read a line.
}
print_r($buffer); // It shows all the text.
Please let me know how to do this?
Thanks.
Regards,
Siva R
It's easier if you use file() since it will get all rows in an array instead:
// Get all rows in an array (and tell file not to include the trailing new lines
$rows = file($filename, FILE_IGNORE_NEW_LINES);
// Remove the first element (first row) from the array
array_shift($rows);
// Now do what you want with the rest
foreach ($rows as $lineNumber => $row) {
// do something cool with the row data
}
If you want to get it all as a string again, without the first row, just implode it with a new line as glue:
// The rows still contain the line break, since we only trimmed the copy
$content = implode("\n", $rows);
Note: As #Don'tPanic pointed out in his comment, using file() is simple and easy but not advisable if the original file is large, since it will read the whole thing into memory as an array (and arrays take more memory than strings). He also correctly recommended the FILE_IGNORE_NEW_LINES-flag, just so you know :-)
You can just call fgets once before your while loop to get the header row out of the way.
$firstline = fgets($handle, 4096);
while (!feof($handle)) // Loop till end of file.
{ ...
I'm trying to display only the rows that contain a specific word in a specific column. Basically I would like to show only the rows that have "yes" in the Display column.
First_Name, Last_Name, Display
Kevin, Smith, yes
Jack, White, yes
Joe, Schmo, no
I've been trying various things with fgetcsv & str_getcsv from other answers and from php.net but nothing is working so far.
It doesn't do anything but this is my current code:
$csv = fopen('file.csv', 'r');
$array = fgetcsv($csv);
foreach ($array as $result) {
if ($array[2] == "yes") {
print ($result);
}
}
Let's have a look at the documentation for fgetcsv():
Gets line from file pointer and parse for CSV fields
fgetcsv reads a single line, not the whole file. You can keep reading lines until you reach the end of the file by putting it in a while loop, e.g.
<?php
$csv = fopen('file.csv', 'r');
// Keep looping as long as we get a new $row
while ($row = fgetcsv($csv)) {
if ($row[2] == "yes") {
// We can't just echo $row because it's an array
//
// Instead, let's join the fields with a comma
echo implode(',', $row);
echo "\n";
}
}
// Don't forget to close the file!
fclose($csv);
You should use data tables.
https://datatables.net/examples/basic_init/zero_configuration.html
That's how I deal with my textfiles. But be carefull, with a large amount of Data (> 10000 rows) you should have a loog at the deferRender option.
https://datatables.net/reference/option/deferRender <-- JSON DATA required.
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");
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).
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);