How to use line feeds in CSV file? - php

I have an excel file that I converted to a CSV so it could be parsed in PHP. However, for some reason the cells in excel only have Carriage Returns (\r) and no Line Feeds (\n). I need line feeds in the csv or else the PHP parses everything in one line, which it shouldn't do.
Is there a way to add line feeds to an excel/csv file?
Thanks!
EDIT: It would seem as though I was exporting the file as the wrong csv—I didn't do Windows Comma Separated. Thanks for the answers guys.

Before you read in your CSV file, do:
ini_set('auto_detect_line_endings', true);
Then set it to false right after reading the file.
From the manual:
This enables PHP to interoperate with Macintosh systems, but defaults
to Off, as there is a very small performance penalty when detecting
the EOL conventions for the first line, and also because people using
carriage-returns as item separators under Unix systems would
experience non-backwards-compatible behaviour.

There are a number of ways to handle it. An easy one in PHP would be to just replace \r with \n before processing it:
// Load the whole data file as a string
$data = file_get_contents("yourcsv.csv");
$data = str_replace("\r","\n", $data);
// use str_getcsv() in PHP 5.3+ to parse it to an array
$csv_array = str_getcsv($data);

Related

php reading csv data into a single line

It's strange PHP Reading my Excel generated CSV file into a single line. Code is:
if ($file) {
while (($line = fgets($file)) !== false) {
print '<div>'.$line.'</div>'."<br/>";
}
} else {
// error opening the file.
}
fclose($file);
CSV
Name, City
Jon,Paris
Doe,Madrid
Add this code before reading the file.
ini_set("auto_detect_line_endings", true);
When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.
This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.
Most likely, PHP is not correctly detecting the line endings in your file. The fgets documentation points this out.
You will probably want to write code like this:
$oldLineEndings = ini_set('auto_detect_line_endings', true);
//your while loop here
ini_set('auto_detect_line_endings', $oldLineEndings);
If you need to actually parse the csv, you may also want to look at fgetcsv.

Define new column data during PHP export

I was told that "\t" would 'tell' Excel that it is a new column data.
However, it is just an empty space and all my single line data are in ONE cell instead of seperate columns.
Did i do anything wrong?
while($row =mysqli_fetch_assoc($result))
{
$contents.=$row['idUsers']."\t";
$contents.=$row['First_Name']."\t";
$contents.=$row['Last_Name']."\t";
$contents.=$row['Email_Address']."\t";
$contents.=$row['Verified']."\n";
}
When you're creating a CSV file for MS Excel, you'll find that Excel's separator is locale specific, so what might work for one person won't necessarily work for another.
One way to try and force the issue is to use a sep=<x> line as the very first line of your CSV file; so if you initially define $content using
$contents = "sep=\t\n";
before starting your while loop, you may find that this allows MS Excel to correctly identify what separator you're using when the file you generate is loaded into Excel
And rather than "roll your own" csv format file, why don't you make use of PHP's built-in fputcsv() function, which will also handle quoting strings and generally simplify things for you
Have you tried the CSV format?
Replace your '\t' by a comma..
while($row =mysqli_fetch_assoc($result))
{
$contents.=$row['idUsers'].",";
$contents.=$row['First_Name'].",";
$contents.=$row['Last_Name'].",";
$contents.=$row['Email_Address'].",";
$contents.=$row['Verified']."\n";
}
http://en.wikipedia.org/wiki/Comma-separated_values

successively loading a folder full of csv files without naming using a php script in Mac Terminal

I'm planning to run a php program from Mac Terminal. I have a folder on my desktop with around 800 .csv files and I need to write a php program that reads through and reads each one so that I can run some transformations on the data it's storing. I know how to parse the .csv once it's loaded but I'm wondering if there is a way to load each file without having to name it explicitly? I don't have a list of the 800 file names but I feel like there has to be a way to just read in all the files in a folder in a loop or something without having the title of each file listed -- I don't have much coding experience, so forgive me if there's an obvious answer of which I'm oblivious.
Thank you!
There are a few way todo this but glob'ing is very straightforward:
<?php
foreach (glob("*.csv") as $filename) {
//do somthing
}
?>
You can loop through all files in a directory using readdir() :http://php.net/manual/en/function.readdir.php.
Once you get the file name using readdir() you can parse it by either breaking the file content into an array and working with the cells by looping through the array using str_getcsv() (requires at least phpv5.3) or the old fashion fgetcsv() to read through the file one line at a time. For each file create a string variable, and after line you read through and transform, simply append the modified line to this string with an end-of-line character appended as well. After reading through the entire file, simply replace the file contents of the original with file_put_contents()

How do you EXPLODE CSV line with a comma in value?

"AMZN","Amazon.com, Inc.",211.22,"11/9/2011","4:00pm","-6.77 - -3.11%",4673052
Amazon.com, Inc. is being treated as 2 values instead of one.
I tried this $data = explode( ',', $s);
How do I modify this to avoid the comma in the value issue?
You should probably look into str_getcsv() (or fgetcsv() if you're loading the CSV from a file)
This will read the CSV contents into an array without the need for exploding etc.
Edit- to expand upon the point made by Pekka, if you're using PHP < 5.3 str_getcsv() won't work but there's an interesting approach here which reproduces the functionality for lesser versions. And another approach here which uses fgetcsv() after creating a temporary file.
Use a dedicated CSV library. It's been explained over and over that parsing file formats like CSV manually is asking for trouble, because you don't know all the variations of CSV and all the rules to do it right.

Read in text file line by line php - newline not being detected

I have a php function I wrote that will take a text file and list each line as its own row in a table.
The problem is the classic "works fine on my machine", but of course when I ask somebody else to generate the .txt file I am looking for, it keeps on reading in the whole file as 1 line. When I open it in my text editor, it looks just as how I would expect it with a new name on each line, but its the newline character or something throwing it off.
So far I have come to the conclusion it might have something to do with whatever text editor they are using on their Mac system.
Does this make sense? and is there any easy way to just detect this character that the text editor is recognizing as a new line and replace it with a standard one that php will recognize?
UPDATE: Adding the following line solved the issue.
ini_set('auto_detect_line_endings',true);
Function:
function displayTXTList($fileName) {
if(file_exists($fileName)) {
$file = fopen($fileName,'r');
while(!feof($file)) {
$name = fgets($file);
echo('<tr><td align="center">'.$name.'</td></tr>');
}
fclose($file);
} else {
echo('<tr><td align="center">placeholder</td></tr>');
}
}
This doesn't work for you?
http://us2.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings
What's wrong with file()?
foreach (file($fileName) as $name) {
echo('<tr><td align="center">'.$name.'</td></tr>');
}
From the man page of fgets:
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Also, have you tried the file function? It returns an array; each element in the array corresponds to a line in the file.
Edit: if you don't have access to the php.ini, what web server are you using? In Apache, you can change PHP settings using a .htaccess file. There is also the ini_set function which allows changing settings at runtime.
This is a classic case of the newline problem.
ASCII defines several different "newline" characters. The two specific ones we care about are ASCII 10 (line feed, LF) and 13 (carriage return, CR).
All Unix-based systems, including OS X, Linux, etc. will use LF as a newline. Mac OS Classic used CR just to be different, and Windows uses CR LF (that's right, two characters for a newline - see why no one likes Windows? Just kidding) as a newline.
Hence, text files from someone on a Mac (assuming it's a modern OS) would all have LF as their line ending. If you're trying to read them on Windows, and Windows expects CR LF, it won't find it. Now, it has already been mentioned that PHP has the ability to sort this mess out for you, but if you prefer, here's a memory-hogging solution:
$file = file_get_contents("filename");
$array = split("/\012\015?/", $file); # won't work for Mac Classic
Of course, you can do the same thing with file() (as has already been mentioned).

Categories