简体   繁体   English

如何用php在txt文件中增加价值

[英]how to add value in txt file with php

I want to add a value (not overwrite!) to a txt file with file_put_contents 我想使用file_put_contents向txt文件添加一个值(不覆盖!)

This is what i have so far: 这是我到目前为止所拥有的:

$fileUserId = fopen("fileUserId.txt", "w") or die("Unable to open file!");
$UserIdtxt = $UserID."||";
file_put_contents("fileUserId.txt", $UserIdtxt, FILE_APPEND);
fclose($fileUserId);

$UserID is an integer, like 1, 2, 3 etc. $UserID是整数,例如1、2、3等。

So when the the UserID is 1, the fileUserId.txt looks like this: 因此,当UserID为1时, fileUserId.txt如下所示:

1||

When there is another user with ID 2, the fileUserId.txt should look like this: 当有另一个ID为2的用户时, fileUserId.txt应该如下所示:

1||2||

But he overwrites the file so it becomes this: 但是他覆盖了文件,因此它变成了:

2||

What i am doing wrong? 我做错了什么?

Remove the fopen and fclose line and you are fine. 删除fopenfclose线,就可以了。 file_put_contents does this internally. file_put_contents在内部执行此操作。 And fopen("fileUserId.txt", "w") clears the file. 然后fopen("fileUserId.txt", "w")清除文件。

Note: 注意:

'w' Open for writing only; w只开放写作; place the file pointer at the beginning of the file and truncate the file to zero length. 将文件指针放在文件的开头,并将文件截断为零长度。 If the file does not exist, attempt to create it. 如果该文件不存在,请尝试创建它。

You can as well do it differently. 您也可以采用其他方式。 The commented code below illustrates how: 下面的注释代码说明了如何:

<?php

    $txtFile    = __DIR__ . "/fileUserId.txt";
    $UserID     = 9; //<== THIS VALUE IS FOR TESTING PURPOSES, 
                     //<== YOU SHOULD HAVE ACCESS TO THE ORIGINAL $UserID;

    //CHECK THAT THE FILE EXISTS AT ALL
    if( file_exists($txtFile) ){
        // GET THE CONTENTS OF THE FILE... & STORE IT AS A STRING IN A VARIABLE
        $fileData       = file_get_contents($txtFile);

        // SPLIT THE ENTRIES BY THE DELIMITER (||)
        $arrEntries     = preg_split("#\|\|#", $fileData);

        // ADD THE CURRENT $UserID TO THE $arrEntries ARRAY
        $arrEntries[]   = $UserID;

        // RE-CONVERT THE ARRAY TO A STRING...
        $strData        = implode("||", $arrEntries);

        // SAVE THE TEXT FILE BACK AGAIN...
        file_put_contents($txtFile, $strData);
    }else{
        // IF FILE DOES NOT EXIST ALREADY, SIMPLY CREATE IT
        // AND ADD THE CURRENT $UserID AS THE FIRST ENTRY...
        file_put_contents($txtFile, $UserID);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM