import.lib.php 2.3 KB

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