import.lib.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This class provides some functions which can be used when importing data from
  5. * external files into Chamilo.
  6. * @package chamilo.library
  7. */
  8. class Import {
  9. /**
  10. * Reads a CSV-file into an array. The first line of the CSV-file should contain the array-keys.
  11. * The encoding of the input file is tried to be detected.
  12. * The elements of the returned array are encoded in the system encoding.
  13. * Example:
  14. * FirstName;LastName;Email
  15. * John;Doe;john.doe@mail.com
  16. * Adam;Adams;adam@mail.com
  17. * returns
  18. * $result [0]['FirstName'] = 'John';
  19. * $result [0]['LastName'] = 'Doe';
  20. * $result [0]['Email'] = 'john.doe@mail. com';
  21. * $result [1]['FirstName'] = 'Adam';
  22. * ...
  23. * @param string $filename The path to the CSV-file which should be imported.
  24. * @return array Returns an array (in the system encoding) that contains all data from the CSV-file.
  25. */
  26. function csv_to_array($filename) {
  27. $result = array();
  28. // Encoding detection.
  29. $handle = fopen($filename, 'r');
  30. if ($handle === false) {
  31. return $result;
  32. }
  33. $buffer = array();
  34. $i = 0;
  35. while (!feof($handle) && $i < 200) {
  36. // We assume that 200 lines are enough for encoding detection.
  37. $buffer[] = fgets($handle);
  38. $i++;
  39. }
  40. fclose($handle);
  41. $buffer = implode("\n", $buffer);
  42. $from_encoding = api_detect_encoding($buffer);
  43. unset($buffer);
  44. // Reading the file, parsing and importing csv data.
  45. $handle = fopen($filename, 'r');
  46. if ($handle === false) {
  47. return $result;
  48. }
  49. $keys = api_fgetcsv($handle, null, ';');
  50. foreach ($keys as $key => &$key_value) {
  51. $key_value = api_to_system_encoding($key_value, $from_encoding);
  52. }
  53. while (($row_tmp = api_fgetcsv($handle, null, ';')) !== false) {
  54. $row = array();
  55. // Avoid empty lines in csv.
  56. if (is_array($row_tmp) && count($row_tmp) > 0 && $row_tmp[0] != '') {
  57. if (!is_null($row_tmp[0])) {
  58. foreach ($row_tmp as $index => $value) {
  59. $row[$keys[$index]] = api_to_system_encoding($value, $from_encoding);
  60. }
  61. $result[] = $row;
  62. }
  63. }
  64. }
  65. fclose($handle);
  66. return $result;
  67. }
  68. }