after setting the delimiter '\t' fgetcsv() truncates the value when it is empty string
workaround:
<?php
$file = new SplFileObject($path);
$file->setFlags(SplFileObject::DROP_NEW_LINE);
while ($file->valid()) {
$line = $file->fgets();
$line = explode("\t", $line);
print_r($line);
}
?>
SplFileObject::fgetcsv
(PHP 5 >= 5.1.0)
SplFileObject::fgetcsv — دریافت خط از فایل و تحلیل فیلدهای CSV
Description
دریافت خط از فایل در قالب CSV و بازکرداندن آرایه شامل فیلدهای خوانده شده.
Parameters
- delimiter
-
جداکننده فیلد (تنها یک کاراکتر). به طور پیشفرض کاما یا مقدار تعیین شده با استفاده از SplFileObject::setCsvControl().
- enclosure
-
کاراکتر شمول فیلد (تنها یک کاراکتر). پیشفرض آن " یا مقدار تعیین شده به وسیله SplFileObject::setCsvControl().
- escape
-
کارکتر گریز (تنها یک کاراکتر). بطور پیشفرض (\) یا مقدار تعیین شده به وسیله SplFileObject::setCsvControl().
Return Values
بازگرداندن آرایه اندیسدار شامل فیلدهای خوانده شده یا FALSE در صورت خطا.
Note:
خط خالی در فایل CSV به شکل آرایهای شامل فیلد NULL بازگردانده میشود مگر این که از SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE استفاده شود که خطوط خالی پرش شوند.
Examples
Example #1 مثال SplFileObject::fgetcsv()
<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
var_dump($file->fgetcsv());
}
?>
Example #2 مثال SplFileObject::READ_CSV
<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
list($animal, $class, $legs) = $row;
printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>
محتوای animals.csv
crocodile,reptile,4 dolphin,mammal,0 duck,bird,2 koala,mammal,4 salmon,fish,0
The above example will output something similar to:
A crocodile is a reptile with 4 legs A dolphin is a mammal with 0 legs A duck is a bird with 2 legs A koala is a mammal with 4 legs A salmon is a fish with 0 legs
See Also
- SplFileObject::setCsvControl() - تعیین جداکننده و کاراکتر شمول برای CSV
- SplFileObject::setFlags() - تعیین پرچم برای SplFileObject
- SplFileObject::READ_CSV
- SplFileObject::current() - بازیابی خط فعلی فایل
Note that due to bugs 55807 and 61032, introduced in 5.3.8, if the csv in example #2 has a newline character at the end of each line, the foreach will execute 6 times.
The last time through the loop $row will be bool(false). This is true even if using SplFileObject::SKIP_EMPTY and SplFileObject::DROP_NEW_LINE.
Until the bug is fixed, the workaround is to also add SplFileObject::READ_AHEAD to your setFlags() call.
