PHP - 如何写在文本文件中的行,如果行的文件已经可以再算上请求

问题描述 投票:0回答:2

我想写这写文本文件中的字符串行一个PHP代码,如果在文本文件中已有行再算上包含例如文本文件的要求:

red.apple:1
big.orange:1
green.banana:1

如果有人要求在文件中添加如果它big.orange文件中已经可以再算上作为big.orange:2如果不可再写入新行big.orange:1

后执行代码的文本文件

    red.apple:1
    big.orange:2
    green.banana:1

我写了下面的代码,但不工作。

<?PHP
$name = $_GET['fname']

$file = fopen('request.txt', "r+") or die("Unable to open file!");

if ($file) {
    while (!feof($file)) {
        $entry_array = explode(":",fgets($file));
        if ($entry_array[0] == $name) {
            $entry_array[1]==$entry_array[1]+1;
            fwrite($file, $entry_array[1]);
        }
    }
    fclose($file);
}    
else{
    fwrite($file, $name.":1"."\n");
    fclose($file);
}
?>
php
2个回答
2
投票

相反,创建自己的格式,你需要手工解析的,你可以简单地使用JSON。

下面是一个关于它是如何工作的建议。这将添加请求fname值,如果它不存在,也将创建文件,如果没有已经存在了。

$name = $_GET['fname'] ?? null;

if (is_null($name)) {
    // The fname query param is missing so we can't really continue
    die('Got no name');
}

$file = 'request.json';

if (is_file($file)) {
    // The file exists. Load it's content
    $content = file_get_contents($file);

    // Convert the contents (stringified json) to an array
    $data = json_decode($content, true);
} else {
    // The file does not extst. Create an empty array we can use
    $data = [];
}

// Get the current value if it exists or start with 0
$currentValue = $data[$name] ?? 0;

// Set the new value
$data[$name] = $currentValue + 1;

// Convert the array to a stringified json object
$content = json_encode($data);

// Save the file
file_put_contents($file, $content);

0
投票

如果您仍然需要使用这种格式(如,这是一些考试测试或传统),请尝试以下功能:

     function touchFile($file, $string) {
        if (!file_exists($file)) {
            if (is_writable(dirname($file))) {
                // create file (later)
                $fileData = "";
            } else {
                throw new ErrorException("File '".$file."' doesn't exist and cannot be created");
            }
        } else $fileData = file_get_contents($file);
        if (preg_match("#^".preg_quote($string).":(\d+)\n#m", $fileData, $args)) {
            $fileData = str_replace($args[0], $string.":".(intval($args[1])+1)."\n", $fileData);
        } else {
            $fileData .= $string.":1\n";
        }
        if (file_put_contents($file, $fileData)) {
            return true;
        } else {
            return false;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.