import.lib.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * @param bool $setFirstRowAsHeader
  18. * @return CsvReader
  19. */
  20. public 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. public static function csvToArray($filename)
  53. {
  54. $csvReader = self::csv_reader($filename);
  55. $resultArray = [];
  56. if ($csvReader) {
  57. $workflow = new Workflow\StepAggregator($csvReader);
  58. $writer = new ArrayWriter($resultArray);
  59. $workflow->addWriter($writer)->process();
  60. }
  61. return $resultArray;
  62. }
  63. }