写入文本文件不适用于单击的第一个项目

时间:2015-07-27 17:56:21

标签: php text fopen file-get-contents file-put-contents

我有一个奇怪的问题,我不知道出了什么问题。我正在编写美国的互动地图。用户单击状态,单击正在文本文件中记录。然后在地图上显示总点击次数。它基本上是围绕完整数据库的快速解决方法。

代码有效。每次单击状态时,都会将其添加到文本文件中。如果状态尚不存在,则为其创建条目。如果是,则只需更新点击次数。这是文件:

<?php 
    // get the input from AJAX
    @$state = $_GET['state'];
    // get the txt file where all of the states are 
    $file = 'state_count.txt';
        //if state_count.txt exists 
        if($fopen = fopen($file, 'c')){ 
            //open it and check if the name of the state is recorded or not 
            if($strpos= strpos(file_get_contents($file), $state)){
                //if so, add 1 to the value after the state's name
                // in the formate State:#
                //cut the text file into an array by lines 
                $lines = file($file);
                //foreach line, parse the text 
                foreach($lines as $l => $k){ 
                    // create a new array $strings where each key is the STATE NAME and each value is the # of clicks 
                    $strings[explode(':', $k)[0]] = explode(':', $k)[1];
                } 
                // add 1 to the # of clicks for the state that was clicked
                $strings[$state] = $strings[$state]+1;  
                // move cursor to the end of the state's name and add 1 to accomodate the : 
                fseek($fopen, $strpos+strlen($state)+1, SEEK_SET); 
                // overwrite number in file
                fwrite($fopen, $strings[$state]); 

                // debug print($strings[$state]);

            }
            //if not, add it with the value 1
            else{ 
                file_put_contents($file, $state.":1\n", FILE_APPEND); 
            } 
        }   
        //if does not exist
        else{ 
            die('Cannot create or open file.'); 
        } 

?>

我遇到的问题是代码适用于所有状态,除了单击的FIRST状态(即文本文件为空,用户单击一个状态,该状态是第一个状态)。在这种情况下,它永远不会更新最初点击的状态,它只是为它创建了一堆单独的条目。它最终看起来像这样(假设我先点击宾夕法尼亚州):

Pennsylvania:1
Pennsylvania:1
Utah:1
Colorado:1
Kansas:1
Nebraska:1
Wyoming:1
Indiana:1
Ohio:3
Virginia:1
West Virginia:2
Kentucky:8
Tennessee:1
Georgia:1
Alabama:2
Mississippi:1
Pennsylvania:1
Pennsylvania:1
Pennsylvania:1
Pennsylvania:1
Pennsylvania:1

我不确定为什么会这样做,所以我希望一双新眼睛可以指出一些明显的东西......我感觉它与if($strpos= strpos(file_get_contents($file), $state)){中的行if语句有关,但我不能确定。代码工作100%正确,但是你点击的第一个状态似乎是一个奇怪的问题。我知道这是第一个状态,因为我已经多次尝试过不同状态作为第一个状态。

有任何想法或建议吗?

1 个答案:

答案 0 :(得分:5)

请注意,当您使用strpos查看字符串是否存在时,您应该检查boolean:

if (strpos(....) !== false) { ... }

否则当你的strpos像你的情况一样返回0时你会有误报。

在您的代码中,您可以这样做:

$strpos= strpos(file_get_contents($file), $state);
if ($strpos !== false) {...