Page 1 of 1

problem in reading the first row header in csv file

Posted: Thu Oct 01, 2009 5:25 am
by phpfan
hello,

my task is to read the first row header, and after reading it, it should break..... i am able to read the first row header but im also getting the second complete row too

kindly help me

Code: Select all

<?php
include "connect.php";
 
if(isset($_POST['submit']))
   {
   $filename=$_POST['filename'];
// open the text file
    $fd = fopen ("$filename", "r");
// initialize a loop to go through each line of the file
    while (!feof ($fd)) 
    {
        $buffer = fgetcsv($fd, 4096); 
// declare an array to hold all of the contents of each
//row, indexed
        //echo "n";
// this for loop to traverse thru the data cols
// when this is re-created with MySQL use the mysql_num_fileds() function to get
// this number
        for ($i = 0; $i < count($buffer); $i++)
        {
            if ($buffer[$i] == "")
            {
                $buffer[$i] = " ";
                echo "</br>";
            }
// print 's with each index
            echo "$buffer[$i]";
            
        }
        //echo "n";
    }
    fclose ($fd);
    }
    else
   {
      print "<form action='file.php' method='post'>";
      print "Type file name to import:<br>";
      print "<input type='text' name='filename' size='20'><br>";
      print "<input type='submit' name='submit' value='submit'></form>";
   }
 
?>

Re: problem in reading the first row header in csv file

Posted: Sun Oct 04, 2009 4:53 am
by pastcow
If its just the first row you want and they are literally just separated by "," then you can do

Code: Select all

 
$f = fopen($filename, "r");
$firstline = fgets($f)
fclose($f);
$fields = explode(",", $firstline);
print_r($fields);
 
otherwise you might have more luck with using the mysql import function - I've never had much luck with fgetcsv - seems it doesnt follow the RFC for CSV files very well. The mysql version would be something like this...

Code: Select all

 
LOAD DATA LOCAL INFILE '$filename'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, filed2, field3);