У меня есть файл CSV, который похож на это
$lines[0] = "text, with commas", "another text", 123, "text",5;
$lines[1] = "some without commas", "another text", 123, "text";
$lines[2] = "some text with commas or no",, 123, "text";
И я хотел бы иметь таблицу:
$t[0] = array("text, with commas", "another text", "123", "text","5");
$t[1] = array("some without commas", "another text", "123", "text");
$t[2] = array("some text, with comma,s or no", NULL , "123", "text");
Если я использую split($lines[0],",")
Я доберусь "text" ,"with commas" ...
Там какой-либо изящный путь состоит в том, чтобы сделать это?
Вы можете использовать fgetcsv
для разбора CSV файла, не заботясь о том, чтобы разбирать его самостоятельно.
Пример из руководства PHP:
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Помимо предложения Мэтта , вы также можете использовать SplFileObject
для чтения файла :
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(',', '"', '\\'); // this is the default anyway though
foreach ($file as $row) {
list ($fruit, $quantity) = $row;
// Do something with values
}
источник: http://de.php.net/manual/en/splfileobject.setcsvcontrol.php
здесь также есть простой метод для чтения файла csv.
$sfp = fopen('/path/to/source.csv','r'); $dfp = fopen('/path/to/destination.csv','w'); while ($row = fgetcsv($sfp,10000,",","")) { $goodstuff = ""; $goodstuff = str_replace("¦",",",$row[2]); $goodstuff .= "\n"; fwrite($dfp,$goodstuff); } fclose($sfp); fclose($dfp);