使用php从文本文件中读取逗号分隔的值


Read comma separated values from a text file using php

我有一个文本文件,它由逗号分隔的内容组成。

设我的文件为test.txt。内容为:

text1, text2, text3

我想读取这个文件,并将这三个值赋给三个变量。

我检查了readfile(filename,include_path,context)

试试这个

$textCnt  = "text.txt";
$contents = file_get_contents($textCnt);
$arrfields = explode(',', $contents);
echo $arrfields[0]; 
echo $arrfields[1]; 
echo $arrfields[2]; 

或者,在循环中:

foreach($arrfields as $field) {
    echo $field;
}

另一个选择是使用fgetcsv,你不需要爆炸的值。

如果您的csv文件使用不同的分隔符,只需将其作为参数传递给fgetcsv

例子
$h = fopen("csv.csv", "r");
while (($line = fgetcsv($h)) !== FALSE) {
    print_r($line);
}
fclose($h);