当前位置:Gxlcms > PHP教程 > php读取csv文件类

php读取csv文件类

时间:2021-07-01 10:21:17 帮助过:26人阅读

  1. define("CSV_Start", 0);
  2. define("CSV_Quoted", 1);
  3. define("CSV_Quoted2", 2);
  4. define("CSV_Unquoted", 3);
  5. function readCSV($fh, $len, $delimiter = ',', $enclosure = '"') {
  6. $data = Array();
  7. $fildNr = 0;
  8. $state = CSV_Start;
  9. $data[0] = "";
  10. do {
  11. $line = fgets($fh, $len);
  12. for ($ix = 0; $ix < strlen($line); $ix++) {
  13. if ($line[$ix] == $delimiter) {
  14. if ($state != CSV_Quoted) {
  15. $fildNr++;
  16. $data[$fildNr] = "";
  17. $state = CSV_Start;
  18. } else {
  19. $data[$fildNr] .= $line[$ix];
  20. }
  21. } elseif ($line[$ix] == $enclosure) {
  22. if ($state == CSV_Start) {
  23. $state = CSV_Quoted;
  24. } elseif ($state == CSV_Quoted) {
  25. $state = CSV_Quoted2;
  26. } elseif ($state == CSV_Quoted2) {
  27. $data[$fildNr] .= $line[$ix];
  28. $state = CSV_Quoted;
  29. } else {
  30. $data[$fildNr] .= $line[$ix];
  31. }
  32. } else {
  33. $data[$fildNr] .= $line[$ix];
  34. if ($state == CSV_Quoted2) {
  35. echo "error";
  36. } elseif ($state == CSV_Start) {
  37. $state = CSV_Unquoted;
  38. }
  39. }
  40. }
  41. } while ($state == CSV_Quoted);
  42. return $data;
  43. }
  44. ?>

php, csv

人气教程排行