• Subcribe to Our RSS Feed

[.CSVFILE] How To Read And Write Data Into *.CSV File In Php

Nov 25, 2012   //   by admin   //   Mysql, Other, PHP  //  No Comments

Hi Friends,

I am giving you tips for how to read and write data into *.CSV file.This functions is very useful whenever you will develop application.some time we have to submit report to customer, client or any one you can use this function and you can send .csv file to any one.This file is also very important in shopping cart application.you can develop export and import product function using this tips.

Put Data or Write Data In *.CSV File

Using this code you can generate .csv file from database.which is function like export to csv.

    <?php 
    $res= mysql_query("SELECT * FROM student");
 
    while ($rows= mysql_fetch_row($res)) {
    for ($j=0;$j<$i;$j++) {
       $csv_data .= $rows[$j].", ";
    }
     $csv_data .= "\n";
    }
 
    $fname= "yourfilename";
 
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$fname.".csv");
 
    print $csv_output;
 
     exit;
    ?>

Get Data or Read Data From *.CSV File

Using this code you can read data from .csv and insert that data to database which is function like import to csv.

  <?php
    $row = 1;
    $filereader= fopen("yourfilename.csv", "r");
    while (($row_data = fgetcsv($filereader, 1000, ",")) !== FALSE) {
 
    $row++;
    for ($counter=0; $counter < $num; $counter++) {
     echo $row_data[$c] . " ";
    }
    //insert to database
       mysql_query("INSERT INTO student('RollNo','Name','Marks') VALUES('".$row_data[0]."','".$row_data[1]."','".$row_data[2]."')"); 
    echo "<br/>"; 
    }
    fclose($filereader);
  ?>

All The Best.
Thanks.

Leave a comment

*

Social Media Auto Publish Powered By : XYZScripts.com