import.lib.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Ddeboer\DataImport\Workflow;
  4. use Ddeboer\DataImport\Reader\CsvReader;
  5. use Ddeboer\DataImport\Writer\ArrayWriter;
  6. /**
  7. * Class Import
  8. * This class provides some functions which can be used when importing data from
  9. * external files into Chamilo.
  10. * @package chamilo.library
  11. *
  12. */
  13. class Import
  14. {
  15. /**
  16. * @param string $path
  17. * @return CsvReader
  18. */
  19. public static function csv_reader($path, $setFirstRowAsHeader = true)
  20. {
  21. if (empty($path)) {
  22. return false;
  23. }
  24. $file = new \SplFileObject($path);
  25. $csvReader = new CsvReader($file, ';');
  26. if ($setFirstRowAsHeader) {
  27. $csvReader->setHeaderRowNumber(0);
  28. }
  29. return $csvReader;
  30. }
  31. /**
  32. * Reads a CSV-file into an array. The first line of the CSV-file should contain the array-keys.
  33. * The encoding of the input file is tried to be detected.
  34. * The elements of the returned array are encoded in the system encoding.
  35. * Example:
  36. * FirstName;LastName;Email
  37. * John;Doe;john.doe@mail.com
  38. * Adam;Adams;adam@mail.com
  39. * returns
  40. * $result [0]['FirstName'] = 'John';
  41. * $result [0]['LastName'] = 'Doe';
  42. * $result [0]['Email'] = 'john.doe@mail. com';
  43. * $result [1]['FirstName'] = 'Adam';
  44. * ...
  45. * @param string $filename The path to the CSV-file which should be imported.
  46. * @return array Returns an array (in the system encoding) that contains all data from the CSV-file.
  47. *
  48. *
  49. * @deprecated use cvs_reader instead
  50. */
  51. public static function csvToArray($filename)
  52. {
  53. $csvReader = self::csv_reader($filename);
  54. $resultArray = [];
  55. if ($csvReader) {
  56. $workflow = new Workflow\StepAggregator($csvReader);
  57. $writer = new ArrayWriter($resultArray);
  58. $workflow->addWriter($writer)->process();
  59. }
  60. return $resultArray;
  61. }
  62. }