如何从PHP中的csv文件中提取数据

liy*_*ysd 19 php csv split

我有一个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";
Run Code Online (Sandbox Code Playgroud)

我想要一张桌子:

$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");
Run Code Online (Sandbox Code Playgroud)

如果我使用split($lines[0],",")我会得到"text" ,"with commas" ... 有没有任何优雅的方式来做到这一点?

Mat*_*att 35

您可以使用它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);
}
Run Code Online (Sandbox Code Playgroud)


Gor*_*don 19

除了Matt的建议,你还可以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
}
Run Code Online (Sandbox Code Playgroud)

来源:http://de.php.net/manual/en/splfileobject.setcsvcontrol.php