douren9077 2013-08-28 23:45
浏览 94

从文本文件php中删除行

i am trying to list all of the lines in a text file and have a delete button next to each one. When the button is pressed that line should be deleted. like below

 Line One Text | Delete
 Line Two Text | Delete
 Line Three Text | Delete

I think i am quite close but cannot get it to work, any ideas why? The lines and buttons display fine, but the delete button does not seem to do anything.

edit.php

<?php
$textFile = file("guestbook.txt");
foreach ($textFile as $key => $val) {
    $line = @$line . $val
        . "<input type='submit' name=$key value='Delete'><br />";
}

$form = "<form name='form' method='post' action='deleter.php'> $line 
    </form>";

echo $form;
?>

deleter.php

if ($delete != "" && $delete > !$lines || $delete === '0') {
    $textFile[$delete] = "";
    $fileUpdate = fopen("data.txt", "wb");
    for ($a = 0; $a < $lines; $a++) {
        fwrite($fileUpdate, $textFile[$a]);
    }
    fclose($fileUpdate);
    header("Location:edit.php");
    exit;
}

foreach ($textFile as $key => $val) {
    $line = @$line . $val . "<a href =?delete=$key> Delete </a><br />";
}
echo $line;
?>

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • doubu4406 2013-08-28 23:54
    关注

    One approach could be to query the server with the string to be removed if no line can be equal to another one, e.g., delete.php?str=<your string> and do the deletion of that string (note that I said 'string' not line).

    If it's possible for lines to be equal, you should identify the lines and follow a similar approach: delete.php?line=<number>.

    This should be easy and you could write a flexible code that deletes lines from a giving file by also passing the filename.

    Edit: Example provided following the advise of using a hidden field.

    <?php
    $html = "<form id='form' method='post' action='delete.php'>";
    foreach(array("line 1", "line 2", "line 3") as $key => $value ) {
        $html .= "<span>${value}</span>";
        $html .= "<input type='hidden' name='lineNumber' value='${key}'>";
        $html .= "<input type='submit' value='Delete' name='line'><br>";
    }
    $html .= "</form>";
    echo $html;
    ?>
    

    In your delete.php get the content of $_POST['lineNumber'] to retrieve the line number.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测