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");
Related
Is it possible to export csv data in to two parts:
From the below image i have two things to be considered
1. summery
2. Detail information
I worked with only 2nd type is it possible to do like 2 batches(like shown in image)..?
please suggest any alternate idea if you got.
Example:
summary header
$titleSummery = array('Course Name','Average watched','semi watched','notwached','sudents attempted','sudents notattempted','Total students','Branch','passout');
/*summery data */
Details header
$titleDetail = array('student','passout','branch','percentage watched','student email');
/*Details data */
In this case how can i export the data..?
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach($data as $k=>$res){
fputcsv($output,$res);
}
You need to prepare array for each line. see my inline comments.
$titleSummery = array('Course Name','Average watched','semi watched','notwached','sudents attempted','sudents notattempted','Total students','Branch','passout');
$titleSummeryData = array('Number System','50%','40%',....); // fill remaining data.
$output = fopen('php://output', 'w');
// put first table
foreach($titleSummery as $key=>$val){
fputcsv($output,array($val,$titleSummeryData[$key]));
}
// begin second table
// put all title/header
fputcsv($output,$titleDetail);
// For second table i assume that you have data in 2D array
foreach($titleDetailsData as $row){
fputcsv($output);
}
fclose($output);
You direction is good, you just need to understand that each call to fputcsv prints a line, so you'll need to call it for each row in the first batch of data also, for example:
fputcsv($output,"course name","php for dummies");
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 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
What I want to do is, to export some dataset for Excel without using extra, 3rd party, heavy libraries.
The problem is, when I export the file, first row looks well, but starting from second row, it puts all $row data into first field of current row.
So I get file with first row properly placed in right columns and starting from second row instead of columns I see whole text in first field seperated by delimiter (comma)
Here is code snippet that I use for result.
$counter=0;
$file = fopen("sample.csv", "w");
foreach ($registrants as $registrant) {
$row = [
'Fullname' => $registrant->fullname,
'Phone' => $registrant->phone,
'Email' => $registrant->email,
];
if ($counter == 0)
fputcsv($file, array_keys($row));
fputcsv($file, $row);
$counter++;
}
fclose($file);
Also tried to
fputcsv($file, array_values($row), ';', ' ');
No success. What am I doing wrong? What is proper way to see correct result on all Excel versions regardless of OS or Excel locale and etc.?
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).