Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP] Jak odczytać dużego CSV ?
Agape
post
Post #1





Grupa: Zarejestrowani
Postów: 384
Pomógł: 13
Dołączył: 16.06.2006

Ostrzeżenie: (0%)
-----


Mam plik csv który zajmuje 140 MB, serwer nie daje rady jest "Out of memory" i zastanawiam sie czy nie da sie jakos partiami wczytywac pliku zeby tylko jego czesc byla w pamieci a pozniej kolejna czesc odczytac i przerobic ? Ewentualnie jakis inny sposob, jestem w kropce, juz 2 godziny nad tym siedze ... w komentarzach w manualu znalazlem klase CsvImporter która niby to robi, ale jak odczytam przed tym plikiem jakis jeszcze wczesniej, to tez mam "Out of memory". Moze daloby sie przerobic jakos ta klase zeby nie zajmowala tyle pamieci ?

  1. <?php
  2. class CsvImporter
  3. {
  4. private $fp;
  5. private $parse_header;
  6. private $header;
  7. private $delimiter;
  8. private $length;
  9. //--------------------------------------------------------------------
  10. function __construct($file_name, $parse_header=false, $delimiter="\t", $length=8000)
  11. {
  12. $this->fp = fopen($file_name, "r");
  13. $this->parse_header = $parse_header;
  14. $this->delimiter = $delimiter;
  15. $this->length = $length;
  16. // $this->lines = $lines;
  17.  
  18. if ($this->parse_header)
  19. {
  20. $this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
  21. }
  22.  
  23. }
  24. //--------------------------------------------------------------------
  25. function __destruct()
  26. {
  27. if ($this->fp)
  28. {
  29. fclose($this->fp);
  30. }
  31. }
  32. //--------------------------------------------------------------------
  33. function get($max_lines=0)
  34. {
  35. //if $max_lines is set to 0, then get all the data
  36.  
  37. $data = array();
  38.  
  39. if ($max_lines > 0)
  40. $line_count = 0;
  41. else
  42. $line_count = -1; // so loop limit is ignored
  43.  
  44. while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE)
  45. {
  46. if ($this->parse_header)
  47. {
  48. foreach ($this->header as $i => $heading_i)
  49. {
  50. $row_new[$heading_i] = $row[$i];
  51. }
  52. $data[] = $row_new;
  53. }
  54. else
  55. {
  56. $data[] = $row;
  57. }
  58.  
  59. if ($max_lines > 0)
  60. $line_count++;
  61. unset($row);
  62. }
  63. return $data;
  64. }
  65. //--------------------------------------------------------------------
  66.  
  67. }
  68. ?>


--------------------
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 22.08.2025 - 04:43