import.lib.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Ddeboer\DataImport\Reader\ExcelReader;
  4. use League\Csv\Reader;
  5. /**
  6. * Class Import
  7. * This class provides some functions which can be used when importing data from
  8. * external files into Chamilo.
  9. *
  10. * @package chamilo.library
  11. */
  12. class Import
  13. {
  14. /**
  15. * @param string $path
  16. * @param bool $setFirstRowAsHeader
  17. *
  18. * @return array
  19. */
  20. public static function csv_reader($path, $setFirstRowAsHeader = true)
  21. {
  22. return self::csvToArray($path);
  23. }
  24. /**
  25. * Reads a CSV-file into an array. The first line of the CSV-file should contain the array-keys.
  26. * The encoding of the input file is tried to be detected.
  27. * The elements of the returned array are encoded in the system encoding.
  28. * Example:
  29. * FirstName;LastName;Email
  30. * John;Doe;john.doe@mail.com
  31. * Adam;Adams;adam@mail.com
  32. * returns
  33. * $result [0]['FirstName'] = 'John';
  34. * $result [0]['LastName'] = 'Doe';
  35. * $result [0]['Email'] = 'john.doe@mail. com';
  36. * $result [1]['FirstName'] = 'Adam';
  37. * ...
  38. *
  39. * @param string $filename the path to the CSV-file which should be imported
  40. *
  41. * @return array returns an array (in the system encoding) that contains all data from the CSV-file
  42. */
  43. public static function csvToArray($filename)
  44. {
  45. if (empty($filename)) {
  46. return [];
  47. }
  48. $reader = Reader::createFromPath($filename, 'r');
  49. if ($reader) {
  50. $reader->setDelimiter(';');
  51. //$reader->stripBom(true);
  52. /*$contents = $reader->__toString();
  53. if (!Utf8::isUtf8($contents)) {
  54. // If file is not in utf8 try converting to ISO-8859-15
  55. if ($reader->getStreamFilterMode() == 1) {
  56. $reader->appendStreamFilter('convert.iconv.ISO-8859-15/UTF-8');
  57. }
  58. }*/
  59. $reader->setHeaderOffset(0);
  60. $iterator = $reader->getRecords();
  61. return iterator_to_array($iterator);
  62. }
  63. return [];
  64. }
  65. /**
  66. * @param string $filename
  67. *
  68. * @return array
  69. */
  70. public static function xlsToArray($filename)
  71. {
  72. if (empty($filename)) {
  73. return [];
  74. }
  75. $file = new \SplFileObject($filename);
  76. $reader = new ExcelReader($file, 0);
  77. return $reader;
  78. }
  79. }