文本文件中的增量编号

时间:2012-11-28 05:40:19

标签: php

我想在文本文件中记录下载

有人来到我的网站并下载了一些东西,它会在文本文件中添加新行,如果它还没有或增加当前文件。

我试过了

$filename = 'a.txt';
$lines    = file($filename);
$linea    = array();

foreach ($lines as $line) 
{ 
    $linea[] = explode("|",$line);
}

$linea[0][1] ++;

$a = $linea[0][0] . "|" . $linea[0][1];

file_put_contents($filename, $a);

但它总是增加1以上

文本文件格式为

 name|download_count

4 个答案:

答案 0 :(得分:2)

你在for循环之外进行递增,只访问[0]元素,所以其他任何地方都没有变化。

这可能看起来像:

$filename = 'a.txt';
$lines = file($filename);

// $k = key, $v = value
foreach ($lines as $k=>$v) { 
    $exploded = explode("|", $v);

    // Does this match the site name you're trying to increment?
    if ($exploded[0] == "some_name_up_to_you") {
        $exploded[1]++;

        // To make changes to the source array,
        // it must be referenced using the key.
        // (If you just change $v, the source won't be updated.)
        $lines[$k] = implode("|", $exploded);
    }        
}

// Write.
file_put_contents($filename, $lines);

尽管如此,您可能应该使用数据库。查看PDO和MYSQL,您将会走向卓越。


修改

要做你在评论中提到的内容,你可以设置一个布尔标志,并在你遍历数组时触发它。如果您只想找一件事,这也可能需要break

...
$found = false;
foreach ($lines as $k=>$v) { 
    $exploded = explode("|", $v);

    if ($exploded[0] == "some_name_up_to_you") {
        $found = true;
        $exploded[1]++;
        $lines[$k] = implode("|", $exploded);
        break; // ???
    }        
}

if (!$found) {
    $lines[] = "THE_NEW_SITE|1";
}

...

答案 1 :(得分:0)

一方面你正在使用一个foreach循环,另一只手只是在将它存储到$a之后只写入你文件的第一行......它让我混淆你在你的文件中有什么.txt档案......

请尝试以下代码...希望它能解决您的问题...

$filename = 'a.txt';
// get file contents and split it...
$data = explode('|',file_get_contents($filename));
// increment the counting number...
$data[1]++;
// join the contents...
$data = implode('|',$data);
file_put_contents($filename, $data);

答案 2 :(得分:0)

为什么不使用PHP数组来跟踪,而不是在文本文件中创建自己的结构?您还应该使用适当的锁定来防止竞争条件:

function recordDownload($download, $counter = 'default')
{
    // open lock file and acquire exclusive lock
    if (false === ($f = fopen("$counter.lock", "c"))) {
            return;
    }
    flock($f, LOCK_EX);

    // read counter data
    if (file_exists("$counter.stats")) {
            $stats = include "$counter.stats";
    } else {
            $stats = array();
    }

    if (isset($stats[$download])) {
        $stats[$download]++;
    } else {
        $stats[$download] = 1;
    }

    // write back counter data
    file_put_contents('counter.txt', '<?php return ' . var_export($stats, true) . '?>');

    // release exclusive lock
    fclose($f);
}

recordDownload('product1'); // will save in default.stats
recordDownload('product2', 'special'); // will save in special.stats

答案 3 :(得分:0)

我个人建议使用json blob作为文本文件的内容。然后你可以将文件读入php,解码它(json_decode),操纵数据,然后重新保存。