how to do this: to get data from a .csv file

Discussion in 'PHP' started by rcajht, Feb 12, 2007.

  1. #1
    hi, I am new to PHP, I want following functions, do I need use mySQL database, xml or not, I read several tutorials, still do not have any idea, anybody can give me a help.

    I need to get the data from a .csv or .txt file.
    for example:
    1. web visitor use a form input "name".
    2. to get that name's data from a .csv or .txt file.
    3. return those data to the web page.

    dgdf 3 5 6
    dddd 5 6 7

    visit input "dddd", then show "5 6 7" to the page.
     
    rcajht, Feb 12, 2007 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You can use the function fgetcsv() to get a csv and parse it into an array.

    http://us2.php.net/fget_csv

    One thing you should be careful of, is that you need to make sure that you clean the users input before you do anything with it. Do not take a user's input from the form field and try to execute anything with it. This would be a big security hole.

    here's a simple script that should be able to get you started.

    
    $file = $userfilename; //make sure to validate and clean this before doing anything with it
    
    $fp = fopen("$file","r");
    // do not do this -- $fp = fopen($_POST['file'],"r");
    
    
    while (($line =fgetcsv($fp, 4000, ",")) !== false){
    
    //data is put into an array
    // $line[0] = first value
    // $line[1] = second value, etc...
    
    
    }
    
    fclose($fp); 
    
    PHP:
     
    jestep, Feb 12, 2007 IP
  3. rcajht

    rcajht Peon

    Messages:
    103
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thanks a lot. I will try it.
     
    rcajht, Feb 12, 2007 IP
  4. technoguy

    technoguy Notable Member

    Messages:
    4,369
    Likes Received:
    306
    Best Answers:
    0
    Trophy Points:
    205
    #4
    I generally use fopen and fread to read csv f iles line by line and use explode to store comma seperated values in variable.
     
    technoguy, Feb 12, 2007 IP