Page 1 of 1
reading csv
Posted: Thu Aug 14, 2008 3:21 am
by qadeer_ahmad
Hi,
I have read about fgetcsv but my problem is that i don't know my csv file is comma delimter or tab delimiter.
How can i handle this issue?
if we access the type of csv i.e. it is tab or comma delimiters then this problem will solved.
Thanks
Re: reading csv
Posted: Thu Aug 14, 2008 3:39 am
by onion2k
Moved to the PHP Code forum because General Discussion is not for coding problems.
You could do it automatically by fetching two rows from the file using each delimiter, so get 2 rows using comma and then get the same two rows using tab, and whichever delimiter gets the same number of columns is the one that the file is using. There's a tiny chance that it'd be wrong if the data happened to contain the text with lots of commas but it's very unlikely.
Or you could just ask the user when they upload the file - have a text field in the form for "what is the delimiter?".
Re: reading csv
Posted: Thu Aug 14, 2008 6:44 am
by qadeer_ahmad
Thanks for reply
actually i am getting bad characters when i am reading tab delimiter csv file just like below
D?a?t?e? ?C?h?a?n?n?e?l?
my code is very simple and below
Code: Select all
// open the text file
$fd_2 = fopen ("csv/AdSense-Report.csv", "r");
// initialize a loop to go through each line of the file
while (!feof ($fd_2))
{
// declare an array to hold all of the contents of each row, indexed
$buffer_2 = fgetcsv($fd_2, 4096);
// start a row for the table
//echo "<tr>\n";
// this for loop is the meat, the 44 represents the number of columns in
//the text file, hey...the world is a hack!
// when this is re-created with MySQL use the mysql_num_fileds() function
//to get this number
//for ($i_2 = 0; $i_2 < 43; ++$i_2){
for ($i_2 = 0; $i_2 < 6; $i_2=$i_2+5)
{
$f0=trim($buffer_2[0]);
$f0=sreplace($f0);
$f1=trim($buffer_2[1]);
$f1=sreplace($f1);
$f2=trim($buffer_2[2]);
$f2=sreplace($f2);
$f3=trim($buffer_2[3]);
$f3=sreplace($f3);
$f4=trim($buffer_2[4]);
$f4=sreplace($f4);
$f5=trim($buffer_2[5]);
$f5=sreplace($f5);
$str=$f0."__".$f1."__".$f2."__".$f3."__".$f4;
echo($str."<br>");
}
//echo "\n";//<strong>End of one row </strong><br>";
}
fclose ($fd_2);
its giving me out put of tab delimiter with wrong character (� if you have firefox you will see this character just like a question sign (?) in box.
but it give fine out put comma delimiter file
Thanks
Re: reading csv
Posted: Thu Aug 14, 2008 8:17 am
by onion2k
The problem is the character encoding of the file. The tab delimited file is saved in some sort of multibyte encoding (UTF8 I expect) will the comma separated file is saved in ASCII or Latin-1 or something. You'll need to work out how to detect what encoding the file is using and make sure you take that into account when you're dealing with the data.