我有一個問題。我試圖從數據庫中獲取一些數據到.csv表中。用php寫入csv問題
$fn=fopen($path.$filename, "w");
$addstring = file_get_contents($path.$filename);
$addstring = 'Azonosito;Datum;Ido;Leiras;IP-cim;allomasnév;MAC-cim;Felhasznalonev;Tranzakcioazonosito;Lekerdezes eredmenye;Vizsgalat ideje;Korrelacios azonosito;DHCID;';
/*$addstring .= "\n";*/
$sql="select * from dhcpertekeles.dhcpk";
$result =mysqli_query($conn, $sql);
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$addstring .= "\n".$row[0].";".$row[1].";".$row[2].";".$row[3].";".$row[4].";".$row[5].";".$row[6].";".$row[7].";".$row[8].";".$row[9].";".$row[10].";".$row[11].";".$row[12].";";
};
};
/*file_put_contents($path.$filename, $addstring);*/
fwrite($fn, $addstring);
fclose($fn);
的數據是以下格式: 第一個addstring包含列名,並且沒有問題
第二(addstring =。)中包含的數據: ID($行[0 ],Date($ row [1]),Time($ row [2]),Description($ row [3]),IP($ row [4]),計算機名稱($ row [5]),MAC ($ row [6]),User($ row [7])(空),Transactionid($ row [8]),查詢結果($ row [9]),查詢時間($ row [10] ($ row [11])(空),DHCID($ row [12])(空)
它基本上是每天上傳到數據庫的DHCP服務器數據。現在,代碼起作用了,它將我想要的所有東西寫入csv,但有兩個問題。
1,某些不可解釋的原因代碼,在包含數據的行之間的csv表中插入一個空行。刪除$ row [12]解決了這個問題。我嘗試刪除特殊字符,將空格轉換爲可以看到的東西,甚至將空字符串轉換爲可以看到的東西。然而,沒有任何實際工作,我什至嘗試file_puts_content(第二個問題相同),而不是fwrite,但沒有。同樣的事情不斷髮生。如果我刪除\ n它將起作用,但第二行將向右錯位1列。
2,由於某種原因,最後2個字符被從csv中刪除。在將其寫入文件之前,要插入到csv中的字符串仍包含上述2個字符。嘗試了fwrite和file_puts_content。
至於.csv格式,數據列被除以;和\ n的行。
也試着用libre office和excel閱讀這個文件,認爲它可能是揮之不去的excel。
在寫入csv時更好地使用fputcsv。這是建議的方式,並會照顧一些骯髒的工作。 – marmeladze