This article is about how to read the CSV files using PHP. I have implemented simple and easy way of handling the CSV file in PHP. I have used PHP inbuilt function called fgetcsv to open and read CSV files. You can use this method to insert the CSV data to MYSQL database.


PHP read csv file:

Now lets see how the code look like. As i mentioned earlier we have used php function called fgetcsv(). This function will gets line from file pointer to parse for CSV fields and return an array.
  • code
  • source
  1. //FUnction to read CSV
  2. function readCSV($csvFile){
  3. //Open the file in read mode
  4. $file_handle = fopen($csvFile, 'r');
  5. //Go through a loop
  6. while (!feof($file_handle) ) {
  7. // get data using fgetcsv and push to an array
  8. $line_of_text[] = fgetcsv($file_handle, 1024);
  9. }
  10. //Close the file after reading
  11. fclose($file_handle);
  12. //return the array of data
  13. return $line_of_text;
  14. }
  15. // Set path to CSV file
  16. $csvFile = 'invoices.csv';
  17. //call the csv reading function
  18. $csv = readCSV($csvFile);
  19. // Output the aarray in to brower
  20. //You can insert to db from here
  21. echo '<pre>';
  22. print_r($csv);
  23. echo '</pre>';
Above function will return you a set of data in php array format. You can go through a loop and insert to database also.



0 التعليقات:

إرسال تعليق

 
3lessons © 2013. All Rights Reserved. Powered by Blogger
Top