PHP分号分隔的文件生成

我正在使用此代码生成分号分隔的文件:

for ($i = 0; $i < 3; $i = $i+1) { array_push($dataArray,"$dataCell1","$dataCell2","$dataCell3","$dataCell4","$dataCell5","$dataCell6","$dataCell7","$dataCell8","$dataCell9","$dataCell10","$dataCell11"); $stringData = rtrim(implode(';', $dataArray), ';'); //rtrim will prevent the last cell to be imploded by ';' $stringData .= "\r\n"; } 

我想要的是:

在这里输入图像说明

(数据以分号隔开,行之间用newLine隔开)

我得到的是: 在这里输入图像说明 (数据以分号隔开,但不添加新行,所有数据都显示在sngle行中)

请告诉我我做错了什么

你的问题是你的逻辑。 在每次迭代中,您都要继续将数据添加到$ dataArray中,而代码中的以下语句将stingData设置为仅在最后一次循环中存在的$ dataArray的内爆值。 在这一点上,$ dataArray包含所有的数据值,因为你持续推进3次迭代。

 $stringData = rtrim(...) 

你想要做的是这样的:

 <?php //concatenation string $stringData = ''; for ($i = 0; $i < 3; $i = $i+1) { //init the array with every iteration. $dataArray = array(); //push your values array_push($dataArray,"$dataCell1","$dataCell2","$dataCell3","$dataCell4","$dataCell5","$dataCell6","$dataCell7","$dataCell8","$dataCell9","$dataCell10","$dataCell11"); //concatenate $stringData .= rtrim(implode(';', $dataArray), ';'); //new line $stringData .= "\r\n"; } //print echo $stringData . "\n"; ?> 

改用fputcsv

 // indexed array of data $data = [ ['col1' => 1, 'col2' => 2, 'col3' => 3], ['col1' => 6, 'col2' => 7, 'col3' => 9], ['col1' => 5, 'col2' => 8, 'col3' => 15], ] // add headers for each column in the CSV download array_unshift($data, array_keys(reset($data))); $handle = fopen('php://output', 'w'); foreach ($data as $row) { fputcsv($handle, $row, ';', '"'); } fclose($handle); 

为了创build一个csv文件, fputcsv确实是最好的方法。

首先将数据保存在“数组数组”中。 这使得处理数据变得更容易:

 $dataArray = array(); for ($i = 0; $i < 3; $i = $i+1) $dataArray[$i] = array($dataCell1,$dataCell2,$dataCell3,$dataCell4,$dataCell5,$dataCell6,$dataCell7,$dataCell8,$dataCell9,$dataCell10,$dataCell11); 

接下来,我们需要创build一个临时文件的句柄,同时也确保我们有权这样做。 然后,我们将使用正确的分隔符将所有数组条目存储在临时文件中。

 $handle = fopen('php://temp', 'r+'); foreach($dataArray as $line) fputcsv($handle, $line, ';', '"'); rewind($handle); 

如果您只是想将结果打印到一个页面,下面的代码将执行:

 $contents = ""; while(!feof($handle)) $contents .= fread($handle, 8192); fclose($handle); echo $contents; 

请注意,在纯html中,不显示换行符。 但是,如果您检查生成页面的源代码,则可以看到换行符。

但是,如果您还想将值保存在可下载的csv文件中,则需要使用以下代码:

 $fileName = "file.csv"; header('Content-Type: application/csv'); header('Content-Disposition: attachement; filename="' . $fileName . '";'); fpassthru($handle); fclose($handle);