簡體   English   中英

PHP-如果文件中已有行,如何在文本文件中寫一行,然后計算請求

[英]PHP - How to write a line in text file if line already available in file then count the request

我想編寫一個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);
}
?>

無需創建需要手動解析的自己的格式,您只需使用json。

以下是有關其工作方式的建議。 如果請求的fname值尚不存在,它將添加請求的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);

如果您仍然需要使用此格式(例如,這是一些考試或舊版),請嘗試使用以下功能:

     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;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM