![](/img/trans.png)
[英]Php script to export mysql table data to a csv, escaping data from certain columns and mapping strings to arrays?
[英]Hide certain table columns from CSV with PHP
我正在使用以下代碼從CSV文件生成HTML表。
我只想顯示具有以下索引的列:
$idsColumnsWanted = array(0,1,19,16);
如何將其應用到現有代碼中?
echo "<table class='table table-bordered'>\n\n";
$f = fopen("users.csv", "r");
$first_line=false;
while (($line = fgetcsv($f)) !== false) {
$row ="";
if($first_line == false) {
$row = "<thead><tr>";
$col= "th";
}
else {
$row = "<tr>";
$col= "td";
}
$is_empty = false;
foreach ($line as $cell) {
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . "</".$col.">";
} else {
$is_empty = true;
}
}
if($first_line == false) $row .= "</tr></thead>";
else $row .= "</tr>";
$first_line=true;
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table>";
您可以嘗試使用in_array()函數,並將索引$ i添加到循環中:
$idsColumnsWanted = array(0,1,19,16);
echo "<table class='table table-bordered'>\n\n";
$f = fopen("users.csv", "r");
$first_line=false;
while (($line = fgetcsv($f)) !== false) {
// Restart column index
$i = 0;
$row ="";
if($first_line == false) {
$row = "<thead><tr>";
$col= "th";
}
else {
$row = "<tr>";
$col= "td";
}
$is_empty = false;
foreach ($line as $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted) continue;
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$is_empty = true;
}
// Increase index
$i++;
}
if($first_line == false) $row .= "</tr></thead>";
else $row .= "</tr>";
$first_line=true;
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table>";
一種可能的解決方案是將您的代碼更改為:
$idsColumnsWanted = array(0,1,19,16);
for($i=0;$i<count($line);$i++) {
if (in_array($i, $idsColumnsWanted)) {
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . "</".$col.">";
} else {
$is_empty = true;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.