PHP - fgetcsv - 分隔符被忽略?
我正在尝试输出 csv 文件中的每一行,似乎分隔符被忽略...我确信我的语法在某个地方是错误的,但似乎无法查明它...
CSV 文件看起来像这样:
ID,Code,Count
TM768889,02001,10
TM768889,02002,10
TM768889,02003,10
TM768889,02004,10
TM768889,02005,10
我正在尝试输出:
0 - ID,Code,Count
1 - TM768889,02001,10
2 - TM768889,02002,10
3 - TM768889,02003,10
4 - TM768889,02004,10
5 - TM768889,02005,10
但是,它输出的是:
0 - ID
1 - Code
2 - Count TM768889
3 - 02001
4 - 10 TM768889
5 - 02002
6 - 10 TM768889
7 - 02003
8 - 10 TM768889
9 - 02004
10 - 10 TM768889
11 - 02005
12 - 10
这是我的代码:
$row = 0;
if(($handle = fopen($_FILES["Filedata"]["tmp_name"], "r")) !== FALSE) {
$string = '';
while(($line = fgetcsv($handle,1000,",")) !== FALSE) {
$num = count($line);
$row++;
for($c=0; $c < $num; $c++) {
$string .= $c.' - '.$line[$c].'<br />';
}
}
fclose($handle);
echo $string;
}
I'm trying to output each line in a csv file, and it seems like the delimiter is being ignored... I'm sure my syntax is wrong somewhere, but can't seem to pinpoint it...
The CSV file looks like this:
ID,Code,Count
TM768889,02001,10
TM768889,02002,10
TM768889,02003,10
TM768889,02004,10
TM768889,02005,10
I'm trying to output:
0 - ID,Code,Count
1 - TM768889,02001,10
2 - TM768889,02002,10
3 - TM768889,02003,10
4 - TM768889,02004,10
5 - TM768889,02005,10
But instead, it's outputting this:
0 - ID
1 - Code
2 - Count TM768889
3 - 02001
4 - 10 TM768889
5 - 02002
6 - 10 TM768889
7 - 02003
8 - 10 TM768889
9 - 02004
10 - 10 TM768889
11 - 02005
12 - 10
Here's my code:
$row = 0;
if(($handle = fopen($_FILES["Filedata"]["tmp_name"], "r")) !== FALSE) {
$string = '';
while(($line = fgetcsv($handle,1000,",")) !== FALSE) {
$num = count($line);
$row++;
for($c=0; $c < $num; $c++) {
$string .= $c.' - '.$line[$c].'<br />';
}
}
fclose($handle);
echo $string;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要费心
fgetcsv
?您只是取出该行并将其吐出来,所以看起来您可以只使用 fgets 来代替:您的问题是您正在为 CSV 文件中的每个值打印出一整行,而不是像您想要的那样将线路作为一个整体。
Why bother with
fgetcsv
? You're just taking the line and spitting it back out, so it seems like you could just usefgets
instead:Your problem is that you are printing out a full line for each value in the CSV file, rather than the line as a whole like you intend.
首先,您的代码不会打印您粘贴的内容。计数器与 $c 变量不匹配。
这就是我得到的结果:
如果您的数据文件不是很大,那么我建议您使用 file() 函数将文件加载到数组中。然后您可以循环遍历数组并输出简单的行值。
如果您需要解析该行,则只需使用explode()函数来获取每个值。
Firstly your code does not print what you pasted. The counter does not match the $c variable.
This is what I get:
If your data file is not huge then I advise you to load the file into an array using the file() function. Then you can loop thru the array and output the value which is simply the line.
If you then need to parse the line then just use the explode() function to get at each value.