rajanikant
rajanikant

Reputation: 9

reading csv file in php

I want to read a csv file line by line. i have written code but it give output in encrypted manner . my code is

$row = 1;
$handle = fopen($_FILES['csv']['tmp_name'], "r");
 while (($data = fgetcsv($handle, 1000,",")) != FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);

Upvotes: 0

Views: 3021

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 10161

here I am submitting some sample code to read data from a csv file.

// Set path to CSV file
$csvFile = 'test.csv';
$file_handle = fopen($csvFile, 'r');
//fgetcsv($file_handle);//skips the first line while reading the csv file, uncomment this line if you want to skip the first line in csv file
while (!feof($file_handle) )
{
    $csv_data[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);

/*echo '<pre>';
print_r($csv_data);
echo '</pre>';*/

foreach($csv_data as $data)
{
    echo "<br>column 1 data = ".$data[0];
    echo "<br>column 2 data = ".$data[1];
}

This code should work for you, even after using this code if still you face problem with encrypted text then I think there would be some problem with document character encoding format.

Upvotes: 1

Marc B
Marc B

Reputation: 360872

This is basically exactly the same as example #1 in the PHP fgetcsv() docs. Check your input file, as there's nothing really in here that would "encrypt" data. If the file's encoded in a foreign character set, and you're outputting on ISO-8859, then you will get "encrypted" output.

Upvotes: 0

Related Questions