2015-09-25 49 views
0

我有一個非常基本的問題,它似乎很簡單,但我陷入了這個概念。使用PHP將CSV輸出爲HTML

我想輸出一個csv到html使用php,這是我想輸出的代碼。

<div class="row"> 
    <div class="col-1"> 
    <div class="in"> 
     <p class="description">FIRST CELL OF ROW HERE</p> 
     <p class="town">SECOND CELL OF ROW HERE</p> 
     <p class="city">THIRD CELL OF ROW HERE</p> 
    </div> 
    </div> 
</div> 

,這裏是我的PHP

<?php 

echo "<html><body><table>\n\n"; 
$f = fopen("test.csv", "r"); 
while (($line = fgetcsv($f)) !== false) { 
    echo "<div class='row'"; 
    foreach ($line as $cell) { 
     echo "<div class='col-1'><div class='in'>"; 
     echo "<p class='description'>" . htmlspecialchars($cell) . "</p>"; 
     echo "<p class='address'>" . htmlspecialchars($cell[1]) . "</p>"; 
     echo "<p class='town'>" . htmlspecialchars($cell[2]) . "</p>"; 
     echo "</div></div>"; 
    } 
    echo "</div>"; 
} 
fclose($f); 
echo "\n</table></body></html>"; 

?> 

任何幫助,因爲我似乎無法獲得第二和第三行中有相應的段落標記正確輸出不勝感激。

回答

2

分析:

while (($line = fgetcsv($f)) !== false) { 
     echo "<div class='row'"; 
     // remove this foreach. You're iterating over the cells 
     // when doing this. That is why $cell works while $cell[1] 
     // does not ($cell is not an array at this point) 
     foreach ($line as $cell) { // <-- remove this foreach 

     echo "<div class='col-1'><div class='in'>";  
// You are using $cell as a scalar and then as an array. It is one 
// or the other, not both. 
echo "<p class='description'>" . htmlspecialchars($cell) . "</p>"; 
echo "<p class='address'>" . htmlspecialchars($cell[1]) . "</p>"; 
echo "<p class='town'>" . htmlspecialchars($cell[2]) . "</p>"; 
echo "</div></div>";  
     } 
     echo "</div>"; 
} 
fclose($f); 
echo "\n</table></body></html>"; 

所以固定在你的代碼的問題,是(和更好的縮進)

while (($line = fgetcsv($f)) !== false) { 
    echo "<div class='row'"; 
    echo "<div class='col-1'><div class='in'>"; 
    echo "<p class='description'>" . htmlspecialchars($line[0]) . "</p>"; 
    echo "<p class='address'>" . htmlspecialchars($line[1]) . "</p>"; 
    echo "<p class='town'>" . htmlspecialchars($line[2]) . "</p>"; 
    echo "</div></div>";  
    echo "</div>"; 
} 
fclose($f); 
echo "\n</table></body></html>";