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

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 304
    Comment on it


    Hi Reader's,
      Welcome to FindNerd, today we are going to discuss, "what is method to read data from CSV file?

    If you want to read your data from "CSV" file in php then you should use fgetcsv() function, which is used to read data from a "CSV" file. This function basically reads all and each line of a "CSV" file and assign values into an array. fgetcsv() function always return the CSV fields in an array on success means it returns "FALSE" on failure.
      So, this is the very easy and simple way to read data from CSV file using fgetcsv() function.

    Note:fgetcsv() function returns an indexed array containing the fields read.

    Syntax of fgetcsv() function:

     fgetcsv(file,length,separator,enclosure,escape)

    Parameters description :

    file: 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: This is a Optional parameters and used as field separator (default is ',')
    enclosure: It is a Optional parameters and used for enclose values.
    escape: This is also a Optional parameters and used as escape character.

    You can see below example:

    Firstly let we have a CSV file file.csv

    Emp_No.,Emp_Name,Salary
     1, Ishan,8000k
     2, Pankaj,9200k
     3, Ayush,6800k

     

    In the given above code reads each line from CSV file and returns an array of values for each field.

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

     

    Output will come following :

    Array
    (
        [0] => Emp_No.
        [1] => Emp_Name
        [2] => Salary
    )
    
    Array
    (
        [0] =>  1
        [1] =>  Ishan
        [2] => 8000k
    )
    
    Array
    (
        [0] =>  2
        [1] =>  Pankaj
        [2] => 9200k
    )
    
    Array
    (
        [0] =>  3
        [1] =>  Ayush
        [2] => 6800k
    )

 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: