我正在使用file_put_contents
函数将变量写入文件:
file_put_contents ( 'C:/myfiledata.csv' , $qtype, FILE_APPEND );
使用的不同值一次又一次地调用此函数$qtype
。因此,它们被附加到文件已经存在的内容中。
因此,三次通话会写入以下内容,例如
WaterMelonBlueBerryBlackBerry
问题是,当我通过以下代码读取文件的内容时,输出为:
Array ( [0] => WaterMelonBlueBerryBlackBerry ) $qtype: WaterMelonBlueBerryBlackBerry 0 1
我需要从数组(或$qtype
)中检索单个值。既然值之间没有分隔commas
,我该怎么办?
$file = fopen('C:/myfiledata.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line); //check
$qtype = implode(',' , $line );
echo '$qtype: '.$qtype; //check
}
fclose($file);
echo "\r\n\n";
echo file_put_contents ( 'C:/myfiledata.csv', '');
echo "\r\n\n";
echo unlink('C:/myfiledata.csv'); //echo is for check
编辑:-我们可以看到我得到的数组fgetcsv($file)
是Array ( [0] => WaterMelonBlueBerryBlackBerry )
。为什么我没有得到类似的东西
Array ( [0] => WaterMelon, [1]=>BlueBerry, [2]=>BlackBerry )
我觉得代码有问题吗?因为值是通过多次调用写入CSV文件的file_put_contents ('C:/myfiledata.csv', $qtype, FILE_APPEND)
,所以单个值是通过单个调用写入的。
编辑:-
如果您希望所有内容都放在逗号分隔的一行中,则只需在内容中添加逗号即可。或者您可以在下面附加换行符示例
// for comma
file_put_contents ( 'C:/myfiledata.csv' , $qtype.',', FILE_APPEND );
// for new line
file_put_contents ( 'C:/myfiledata.csv' , $qtype."\n", FILE_APPEND );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句