import.lib.php 2.1 KB

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