Tuesday, March 29, 2011

Reading CSV File in PHP

php csv
The comma-separated values file format is a set of file formats used to store tabular data in which numbers and text are stored in plain textual form that can be read in a text editor. Lines in the text file represent rows of a table, and commas in a line separate what are fields in the tables row. Different implementations of CSV arise as the format is modified to handle richer table content such as allowing a different field separator character, (which is useful if numeric fields are written with a comma instead of a decimal point); or extensions to allow numbers, the separator character, or newline characters in text fields.

A file format is a particular way to encode information for storage in a computer file. Particularly, files encoded using the CSV format are used to store tabular data. The format dates back to the early days of business computing and is widely used to pass data between computers with different internal word sizes, data formatting needs, and so forth. For this reason, CSV files are common on all computer platforms.

As the Web evolves more and more applications go online, generally to feed data to the new system from existing system we use CSV files for it. PHP as the most popular language for web programming offer many ways to read a CSV file, we consider here two ways of doing it, firstly

The Usual Way

In this example we are considering a file is uploaded through a web form,
        ...
        ...
        ...
        
       $newLineChar="\n";
       $delimeter=",";

       $fileHandle=fopen($_FILES["CSVFILE"]["tmp_name"], 'r');
       $contents = fread ($fileHandle,filesize ($_FILES["CSVFILE"]["tmp_name"]));
       fclose($fileHandle);

       $lines=explode($newLineChar, $contents);

       // dividing contents of file line by line

       foreach($lines as $line){
           
           $values=explode($delimeter, trim($line));

           // we trim it because line break char is still there
           // trim removes it !

           echo $values[0]."
"; echo $values[1]."
"; echo $values[2]."
"; // you can traverse values using foreach // also by the above method if you have // few values like i have } .... .... ....
here we divide and conquer technique first we split the contents of line line by line and the split each line by it delimiter and the read it, this is the most easy and simple method to me :)

PHP had a function to deal with CSV let give a look at it too...

fgetcsv

fgetcsv — Gets line from file pointer and parse for CSV fields, Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Method Signature

array fgetcsv ( resource $handle 
[, int $length = 0 
[, string $delimiter = ',' 
[, string $enclosure = '"' 
[, string $escape = '\\' 
]]]] )

Parameters

handle: A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
length: Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is not limited, which is slightly slower.
delimiter: Set the field delimiter (one character only).
enclosure: Set the field enclosure character (one character only).
escape: Set the escape character (one character only). Defaults as a backslash.

Return Values

Returns an indexed array containing the fields read.
Note:A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
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.
Note:Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Example

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "

$num fields in line $row:

\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "
\n"; } } fclose($handle); } ?>

0 comments:

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems