使用fwrite从文本文档中删除特定数据?

时间:2013-04-20 04:01:20

标签: php html mysql fwrite

我正在为我的迷你社交网络编写一个“unfriend”脚本,基本上unfriend action需要从他们的朋友列表中移除他们的名为$user的ID,并且我的ID称为:$my_id。我已经为每个用户文件创建了添加用户ID的脚本,但我不确定如何删除它?

我的friend_list文件: 1,2,3 // I am user 1

他们的friend_list文件: 1,2,3 // They are user 3

我目前使用它将每个id添加到文本文件中:

if($action === 'accept'){
    mysql_query("DELETE FROM `friend_req` WHERE `from`='$user' AND `to`='$my_id'");

    $fp = fopen($user_data['friend_list'], 'a');
    fwrite($fp, ",".$user."");
    fclose($fp);

    $their_id = friend_list_from_user_id($user);
    $fp = fopen($their_id, 'a');
    fwrite($fp, ",".$my_id."");
    fclose($fp);
}

但要从他们的$my_id中删除friend_list以及从$user中删除friend_list个ID,我认为我需要使用类似的内容,但它不起作用:

if($action === 'unfriend'){
    $fp = fopen($user_data['friend_list'], 'a');
    unset($user);
    fclose($fp);

    $their_id = friend_list_from_user_id($user);
    unset($my_id);
    fclose($fp);
}

但这似乎不起作用,我该怎么办才能从相应的文件中删除指定的用户名?

哦,而且,这可能/可能没有用:

$myFile = $file;
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);

$friend = explode(',', $theData);

for($i=0; $i < count($friend); $i++){
    if($i >= 0)
    {
        if($friend[$i] == $user_id) {
        $their_user_id = $user_id;
    }
}

1 个答案:

答案 0 :(得分:0)

要解决您的问题,请执行以下操作:

//get the contents of the file
$contents = file_get_contents($user_data['friend_list']);
$contents = str_replace(",".$friend_id, "", $contents); //remove the friend's id

//open the file again and rewrite the whole thing with the new contents without that id
$fp = fopen($user_data['friend_list'], 'w+');
fwrite($fp, $contents);
fclose($fp);