为什么Excel以随机方式(PHP)生成我的CSV?

我正在使用PHP将数据写入CSV ,但Excel似乎将我的数据排列成随机行。 这里是代码:

  <?php header('Content-type: text/csv'); header('Content-Disposition: attachment; filename="Titles.csv"'); // do not cache the file header('Pragma: no-cache'); header('Expires: 0'); // create a file pointer connected to the output stream $file = fopen('php://output', 'w'); $keywords = $_POST['keywords']; $copytext = $_POST['copytext']; $brand = $_POST['brand']; $KeywordArray = explode(',', $keywords); $CopyTextArray = explode(',', $copytext); $BrandArray = explode(',', $brand); $RandomCopy = array_rand($CopyTextArray, 3); $RandomBrand = array_rand($BrandArray, 3); echo "Keyword,Title\n"; foreach ($KeywordArray as $element) { echo $element.","; echo $element." "; echo $CopyTextArray[$RandomCopy[rand(0,2)]]." "; echo $BrandArray[$RandomBrand[rand(0,2)]]."\n"; } ?> 

这里是我的意思的一个例子(请注意,第12行是我想如何组织数据:

例:

例

有人可以帮我这个吗?

你可以通过做一些相应的改变来使用下面的代码

  $fileName = 'abc'; $file = DIR_DOWNLOAD.$fileName.'.csv' ; $mask = basename($file); $fp = fopen($file, "w"); $feilds = array('product_id','boost','status'); fputcsv($fp, $feilds); foreach($mappingResults->rows as $row){ fputcsv($fp, $row); } fgetcsv($fp, 1000, ","); fclose($fp); header('Content-Type:text/csv'); header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename="' . ($mask ? $mask : basename($file)) . '"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); 

在这里您可以将$mappingResults->rows更改$mappingResults->rows您的数组名称$KeywordArray

希望这会有所帮助。