Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to read data from CSV file

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 104
    Comment on it

    In PHP it is very easy to read data from CSV file using fgetcsv(), which is used to read data from a CSV file. This function reads each line of a CSV file and assign values into an array. The function returns the array of CSV fields. It returns FALSE on failure and at EOF(End Of File).


    Syntax : fgetcsv(file_pointer,length,separator,enclosure,escape)

    Description of function parameters :

    file_pointer: File pointer, Specifies the CSV file (Required)
    length: Maximum line length (in Characters). Omitting this parameter (or setting it to 0) the line length is not limited. (Optional from PHP 5)
    separator: A character used as field separator (default is ','). (Optional)
    enclosure: A character used for enclose values. (Optional)
    escape: A character used as escape character. (Optional)

    Example : Let we have a CSV file test.csv from which we want to read data.
    test.csv
    Roll No.,Name,Marks
    1,Amit Kumar,80
    2,Ashish,92
    3,XYZ,68


    Below is the code which reads each line from CSV file and returns an array of values for each field.

    <?php
    //------open CSV file---------
    $file = fopen('test.csv', 'r');
    
    //--------read data from file----------
    while (($line = fgetcsv($file, 0, ",")) !== FALSE)
      {
        echo "<pre>";
        print_r($line);
        echo "</pre>";
      }
    
    fclose($file);
    ?>
    

    Output :

    Array
    (
        [0] =&gt; Roll No.
        [1] =&gt; Name
        [2] =&gt; Marks
    )
    
    Array
    (
        [0] =&gt; 1
        [1] =&gt; Amit Kumar
        [2] =&gt; 80
    )
    
    Array
    (
        [0] =&gt; 2
        [1] =&gt; Ashish
        [2] =&gt; 92
    )
    
    Array
    (
        [0] =&gt; 3
        [1] =&gt; XYZ
        [2] =&gt; 68
    )
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: