import.lib.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. ==============================================================================
  5. * This class provides some functions which can be used when importing data from
  6. * external files into Dokeos
  7. * @package dokeos.library
  8. ==============================================================================
  9. */
  10. class Import
  11. {
  12. /**
  13. * Reads a CSV-file into an array. The first line of the CSV-file should
  14. * contain the array-keys.
  15. * Example:
  16. * FirstName;LastName;Email
  17. * John;Doe;john.doe@mail.com
  18. * Adam;Adams;adam@mail.com
  19. * returns
  20. * $result [0]['FirstName'] = 'John';
  21. * $result [0]['LastName'] = 'Doe';
  22. * $result [0]['Email'] = 'john.doe@mail. com';
  23. * $result [1]['FirstName'] = 'Adam';
  24. * ...
  25. * @param string $filename Path to the CSV-file which should be imported
  26. * @return array An array with all data from the CSV-file
  27. */
  28. function csv_to_array($filename) {
  29. $result = array();
  30. $handle = fopen($filename, 'r');
  31. if ($handle === false) {
  32. return $result;
  33. }
  34. // Modified by Ivan Tcholakov, 01-FEB-2010.
  35. //$keys = fgetcsv($handle, 4096, ";");
  36. $keys = api_fgetcsv($handle, null, ';');
  37. //
  38. // Modified by Ivan Tcholakov, 01-FEB-2010.
  39. //while (($row_tmp = fgetcsv($handle, 4096, ";")) !== FALSE) {
  40. while (($row_tmp = api_fgetcsv($handle, null, ';')) !== false) {
  41. //
  42. $row = array();
  43. //avoid empty lines in csv
  44. if (is_array($row_tmp) && count($row_tmp) > 0 && $row_tmp[0] != '') {
  45. if (!is_null($row_tmp[0])) {
  46. foreach ($row_tmp as $index => $value) {
  47. $row[$keys[$index]] = $value;
  48. }
  49. $result[] = $row;
  50. }
  51. }
  52. }
  53. fclose($handle);
  54. return $result;
  55. }
  56. }