import.lib.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. *
  17. * @param string $path
  18. * @return \CsvReader
  19. */
  20. static function csv_reader($path, $setFirstRowAsHeader = true)
  21. {
  22. if (empty($path)) {
  23. return false;
  24. }
  25. $file = new \SplFileObject($path);
  26. $csvReader = new CsvReader($file, ';');
  27. if ($setFirstRowAsHeader) {
  28. $csvReader->setHeaderRowNumber(0);
  29. }
  30. return $csvReader;
  31. }
  32. /**
  33. * Reads a CSV-file into an array. The first line of the CSV-file should contain the array-keys.
  34. * The encoding of the input file is tried to be detected.
  35. * The elements of the returned array are encoded in the system encoding.
  36. * Example:
  37. * FirstName;LastName;Email
  38. * John;Doe;john.doe@mail.com
  39. * Adam;Adams;adam@mail.com
  40. * returns
  41. * $result [0]['FirstName'] = 'John';
  42. * $result [0]['LastName'] = 'Doe';
  43. * $result [0]['Email'] = 'john.doe@mail. com';
  44. * $result [1]['FirstName'] = 'Adam';
  45. * ...
  46. * @param string $filename The path to the CSV-file which should be imported.
  47. * @return array Returns an array (in the system encoding) that contains all data from the CSV-file.
  48. *
  49. *
  50. * @deprecated use cvs_reader instead
  51. */
  52. static function csvToArray($filename)
  53. {
  54. $csvReader = self::csv_reader($filename);
  55. $resultArray = [];
  56. if ($csvReader) {
  57. $workflow = new Workflow($csvReader);
  58. $writer = new ArrayWriter($resultArray);
  59. $workflow->addWriter($writer)->process();
  60. }
  61. return $resultArray;
  62. }
  63. }