文件开头的意外空间

时间:2016-06-28 10:21:39

标签: php

对于我的PHP课程,我必须创建一个以示例文本开头的记事本,当我编辑它并单击保存按钮时,文件内的文本将被编辑和保存。因此,如果我刷新页面/直接打开文件,我会显示用户编辑的新内容。

它可以工作,但我的文件中有一些意想不到的空间。

如果我放在第一行的第一个字符"示例文本",我将不会看到"示例文本"但相反:

      sample text 

这仅适用于第一行,如果我手动或使用我的页面编辑文件的话。所有下一行都从第一个字符开始。

在我的notes.txt文件(我的笔记所在的)下面,从网页编辑后:

Mes jeux préférés:
    => Fallout 3
    => Natural Selection 2
    =&#6    2; L4D2

我在文件的开头没有看到任何奇怪的字符。

的index.php:

<?php

define('FICHIER_DE_NOTES', 'notes.txt');
$fichier = fopen(FICHIER_DE_NOTES, 'r+');

if (array_key_exists('note', $_POST)) {

    $note = filter_var($_POST['note'], FILTER_SANITIZE_SPECIAL_CHARS);
    ftruncate($fichier, 0);
    fseek($fichier, 0);
    fputs($fichier, $note);
    $updateMessage = 'Vos notes ont été sauvegardés!';

} else {

    $note = '';

    while ($ligne = fgets($fichier)) {
        $note = $note . $ligne;
    }
}

fclose($fichier);

include 'index.phtml';
?>

我的index.phtml:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bloc Note</title>
</head>
<body>
    <h1>Bloc Note</h1>

    <form method="post" action="index.php" >
        <p>Voici votre bloc note. Ajoutez-y du texte et cliquer sur "Sauvegarder".</p>

        <textarea id="textarea" name="note" rows="16" cols="50">
            <?= $note ?>
        </textarea>
        <br/><br/>
        <label>
            <input type="submit" value="Sauvegarder">
        </label>
        <?php if (isset($updateMessage)) {
            echo $updateMessage;
        } ?>
    </form>

</body>
</html>

我使用vim和PHP5。

告诉我您是否需要更多信息。

3 个答案:

答案 0 :(得分:5)

空白来自您的HTML:

<textarea id="textarea" name="note" rows="16" cols="50">
    <?= $note ?>
</textarea>

您应该使用以下内容:

<textarea id="textarea" name="note" rows="16" cols="50"><?php echo $note ?></textarea>

答案 1 :(得分:3)

这是因为HTML文件的标记中有额外的空格:

    <textarea id="textarea" name="note" rows="16" cols="50">
        <?= $note ?>
    </textarea>

尝试做:

    <textarea id="textarea" name="note" rows="16" cols="50"><?= $note ?></textarea>

答案 2 :(得分:1)

更新你的html:

<textarea id="textarea" name="note" rows="16" cols="50"><?php echo $note ?></textarea>

或者在你的php脚本中:

if (array_key_exists('note', $_POST)) {
   $_POST['note'] = trim($_POST['note']); //added this line
   $note = filter_var($_POST['note'], FILTER_SANITIZE_SPECIAL_CHARS);
   ftruncate($fichier, 0);
   fseek($fichier, 0);
   fputs($fichier, $note);
   $updateMessage = 'Vos notes ont été sauvegardés!';

} else {

   $note = '';

   while ($ligne = fgets($fichier)) {
      $note = $note . $ligne;
    } 
}
相关问题