1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

reading csv file by line

Discussion in 'PHP' started by dizyn, Dec 18, 2008.

  1. #1
    Hi all


    I want to read a csv file line by line. What should be the 2nd argument of fread so that i can read line by line

    
    
    if (!$handle = fopen($filename, 'w+'))
    {
    	echo "Cannot open file ($filename)";
    	exit;
    }
    else
    {
            fread($handle,....);
            fclose($handle);
    }
    
    PHP:
     
    dizyn, Dec 18, 2008 IP
  2. dizyn

    dizyn Active Member

    Messages:
    251
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #2
    this worked
     
    dizyn, Dec 18, 2008 IP
  3. Yesideez

    Yesideez Peon

    Messages:
    196
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Try using file() to read it in - reads the entire file into an array.
    $csvfile=file($filename);
    PHP:
    To access it:
    Line 1 is $csvfile[0]
    Line 2 is $csvfile[1]
    Line 3 is $csvfile[2]

    and so-on...

    To extract the data from each line (presuming it's a comma delimited CSV file:
    $parts=explode(",",$csvfile[0]);
    PHP:
    Just replace the 0 with the line number or you can set up a loop:
    for each ($csvfile as $dat) {
      $parts=explode(",",$dat);
    }
    PHP:
    Once exploded into $parts that is treated as an array as well:
    Element 1 is $parts[0]
    Element 2 is $parts[1]
    Element 3 is $parts[2]

    You can use count() to check how many lines there are:
    $linecount=count($csvfile);
    PHP:
    Although... there are actually functions built-in to PHP that are meant for handling CSV files...
    uk2.php.net/fgetcsv
     
    Yesideez, Dec 18, 2008 IP
  4. herbacious

    herbacious Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    use fgetcsv instead and you don't have to worry about exploding the line into columns
     
    herbacious, Dec 19, 2008 IP