PHP read in from CSV file

Discussion in 'PHP' started by simacaj, Nov 10, 2009.

  1. #1
    Hello all -

    I am still learning a lot about php and have written a piece of code that will extract data from a csv file. It works fine and inserts the records into a mysql database.

    What I am looking for is if there is a easier way to get the data from the data array.

    The first column in the array is always the productid and the rest of the fields are categoryids. Like I said, this works but was wondering if there was a more efficient way of doing this.

    
    
    //Input CSV file
    $fileName = "products.csv";
    
    //Open CSV file	
    $handle = fopen($fileName, "r");
    
    while (($data = fgetcsv($handle, filesize($fileName), ",")) !== FALSE) {
          //Counts number of fields in each row
          $num = count($data);
    
    		for ($c=0; $c < $num; $c++) {
    			if ($c == 0)
    				{
    				$productID = $data[$c];
    			}else {
    				$categoryID = $data[$c];
    			}
    			
    				
    			if ($c > 0){
    				insertRecord($productID, $categoryID);
    				echo "Insert productid: ". $productID . " for categoryid: " . $categoryID . "<br />";
    			}
    		}
    
    PHP:

     
    simacaj, Nov 10, 2009 IP
  2. n3r0x

    n3r0x Well-Known Member

    Messages:
    257
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    120
    #2
    There´s a way to load CSV files directly into MySQL..
    Using the Load data infile You can read about it here
     
    n3r0x, Nov 10, 2009 IP