SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/ImportCSV.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use Exception;
  17.  
  18.  
  19. /**
  20. * Facilitates the cimple importing of CSV files
  21. * Loads up the CSV and allows for sequential reading of the file as data records.
  22. **/
  23. class ImportCSV
  24. {
  25. private $handle;
  26. private $line;
  27. private $headings;
  28.  
  29.  
  30. /**
  31.   * Opens a CSV for reading
  32.   *
  33.   * @param string|resource $filename If a string, the file with that name will be opened as a resource
  34.   * @param array|null $headings Headings for the columns in the CSV.
  35.   * If not provided, they will be extracted from the first row of the CSV
  36.   */
  37. public function __construct($filename, array $headings = null)
  38. {
  39. if (is_string($filename)) {
  40. $this->handle = @fopen($filename, 'r');
  41. } else if (is_resource($filename)) {
  42. $this->handle = $filename;
  43. } else {
  44. throw new Exception('Invalid argument');
  45. }
  46.  
  47. if ($headings) {
  48. $this->headings = $headings;
  49. } else {
  50. $this->headings = fgetcsv($this->handle);
  51. foreach ($this->headings as &$val) {
  52. $val = trim($val);
  53. }
  54. }
  55. }
  56.  
  57. /**
  58.   * Get the headings of this CSV
  59.   **/
  60. public function getHeadings()
  61. {
  62. return $this->headings;
  63. }
  64.  
  65. /**
  66.   * Get a line of the CSV
  67.   **/
  68. public function getLine()
  69. {
  70. if ($this->handle == null) return null;
  71.  
  72. $line = fgetcsv($this->handle);
  73. if ($line == false) {
  74. fclose($this->handle);
  75. $this->handle = null;
  76. return null;
  77. }
  78.  
  79. return $line;
  80. }
  81.  
  82. /**
  83.   * Get a line, and transpose the header line, to create an assoc. array of data
  84.   **/
  85. public function getNamedLine()
  86. {
  87. $line = $this->getLine();
  88. if (! $line) return null;
  89.  
  90. $out = array_flip($this->headings);
  91. foreach ($out as $key => $idx) {
  92. $out[$key] = $line[$idx];
  93. }
  94.  
  95. return $out;
  96. }
  97.  
  98. }
  99.  
  100.  
  101.