读取csv文件并使用php创建另一个csv文件 [英] Read a csv file and create another csv file using php
问题描述
我有一个 .csv
文件,当我通过记事本打开它,它看起来像:
I have a .csv
file and when I open it via notepad it looks like:
ID501501503502
当我通过php在浏览器中打印时
And when I print it in the browser via php, it looks like
ID 501 501 503 502
我的代码是:
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0);
$fh = fopen('php://output', 'w');
if (! empty($data)) {
foreach ($data as $item) {
echo $item."<br>";
//fputcsv($fh, array($item));
}
}
/ code>标签里面的for循环不工作。这是我的第一个问题。
So basically the br
tag inside the for loop doesn't work.This is my first problem.
第二个问题是,即使我使用 fputcsv(现在它已关闭)
它不会创建实际的 csv
文件。
And the second problem is even if I use fputcsv(now it is turned off)
it doesn't create a actual csv
file.
现在我的问题是它是如何在记事本中没有空间的,当我在浏览器中打印它获得空间?
Now my question is how come it has got no space in notepad and when I print in browser it gets space?
我只有一列,没有
任何帮助都非常感谢。提前感谢。
Any help is highly appreciated. Thanks in advance.
推荐答案
如我在注释中提到的,它看起来像原始文件以UNIX行结尾保存,然后您在Windows中使用 fgetcsv
,因此整个文件被读取为一行。在整个输出结尾可能有一个< br>
。
As mentioned in my comment, it looks like your original file is saved with UNIX line endings, and then you're using fgetcsv
in Windows, so the whole file is being read as one line. There's probably one <br>
at the end of the whole output.
在Linux上,实用程序 unix2dos
会执行所需的操作。或者,您可以直接在文件中用 \r\\\
替换
\\\
。
On Linux, the utility unix2dos
does what you want. Or, you can simply replace \n
with \r\n
in your file.
另一个问题是 fgetcsv
不会将整个文件转换成数组。相反,它从文件句柄中读取一行,并将其转换为数组。你需要读取循环中的行:
The other problem is that fgetcsv
does not turn an entire file into an array. Instead, it reads a single line from your file handle, and converts that to an array. You'll need to read lines inside a loop:
while (($data = fgetcsv($handle)) !== FALSE) {
// $data contains one line of the CSV, in array form
// now you can fputcsv the single line
}
这篇关于读取csv文件并使用php创建另一个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!