【发布时间】:2011-10-18 13:00:41
【问题描述】:
我正在编写一个网页,它将在表格中显示 CSV 文件的内容,我想在每一行的末尾添加一个删除按钮,以删除 CSV 文件中的该行,但我有一些删除按钮的问题。这是我目前所拥有的:
<?php
$fileName = "Contacts.csv";
echo "<table> \n\n";
$f = fopen("Contacts.csv", "r");
$i=0;
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo " <td> " . htmlspecialchars($cell) . " </td> ";
}
echo "<td><button type=\"button\" onclick= ?????? >Delete</button></td>";
echo "</tr>\n";
$i++;
}
fclose($f);
echo "\n</table>";
$string="Hello";
?>
然后我在网上找到了一个用于删除 CSV 中的行的函数,它带有两个参数,即 CSV 文件的名称和要删除的行的编号。
function delLineFromFile($fileName, $lineNum){
// check the file exists
if(!is_writable($fileName))
{
// print an error
print "The file $fileName is not writable";
// exit the function
exit;
}
else
{
// read the file into an array
$arr = file($fileName);
}
// the line to delete is the line number minus 1, because arrays begin at zero
$lineToDelete = $lineNum-1;
// check if the line to delete is greater than the length of the file
if($lineToDelete > sizeof($arr))
{
// print an error
print "You have chosen a line number, <b>[$lineNum]</b>, higher than the length of the file.";
// exit the function
exit;
}
//remove the line
unset($arr["$lineToDelete"]);
// open the file for reading
if (!$fp = fopen($fileName, 'w+'))
{
// print an error
print "Cannot open file ($fileName)";
// exit the function
exit;
}
// if $fp is valid
if($fp)
{
// write the array to the file
foreach($arr as $line) { fwrite($fp,$line); }
// close the file
fclose($fp);
}
echo "Contact was deleted successfully!";
}
所以实际上问题是我不知道如何在函数delLineFromFile中放置适当数量的要删除的行。 有人知道怎么做吗?
【问题讨论】:
-
为每一行增加一个变量
$i并将其添加到name=属性中? -
我尝试朝那个方向做一些事情,但后来我不知道如何使用按钮名称为 delLineFromFile() 函数生成输入
-
标题可能相似,但问题不同
-
也许您想改用Python and csv module。否则,您可能会考虑其他方法:不删除文件,而是将 csv 行拆分为单独的数组,内爆,然后在没有删除的值的情况下回写。 Try.