我有一個PHP文件,它從CSV文件中提取信息併成功將其轉換爲僅顯示特定行和列的表格。引用CSV文件中顯示的文件而不是換行字段
但是,CSV文件中的條目中包含逗號和空格,並用引號括起來。由於逗號,我的PHP文件將這些條目拆分爲兩部分,並顯示引號而不是使用引號表示這是一個包含逗號和空格的字段。
例如,CSV文件看起來像這樣:
AA,BB,"Surname, Initial",CC,DD,EE
「姓,並初步」應該是在結果表同場,但正在建立,而不是兩個字段。
我真的想在PHP代碼中解決這個問題,而不是通過修改CSV文件本身。代碼在這裏:
echo "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>
<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\">";
$file = 'CSV/test.csv';
$lines = file($file);
if (file_exists($file)){
//echo "$file exists<br/>";
echo '<table>'; //create the html table
$x=2; //define the first line to display
$y=20; //define the last line to display
$line_counter=0;
foreach ($lines as $line) { //loop to fill your table with csv data
if($x<=$line_counter && $line_counter<=$y)
{
$expl = explode(",", $line); //explode each line on "," to create the rows
echo "<tr>"; //create each line of your table
$c=0;
while ($c<=47) { //loop to extract columns 2 to 47
if(($c % 2) == 1){ //odd rows
echo "<td class=\"odd\">".$expl[$c]."</td>";
}
elseif(($c == 0)){
echo "<td class=\"even\">".$expl[$c]."</td>";
}
else{
echo "<td class=\"even\">".$expl[$c]."</td>"; //even rows
}
$c++;
}
echo "</tr>";
$x++;
}
$line_counter++;
}
echo "</table>";
}
你爲什麼不使用內置的[fgetcsv()](http://www.php.net/manual/en/function.fgetcsv.php)函數來處理文件讀取....它是專門爲此目的而編寫的,並且會爲你處理引號,並且你的問題會奇蹟般地消失 –