douyi5822 2013-01-30 07:32
浏览 26
已采纳

PHP从文本文件写入和读取

I have an issue with writing and reading to text file.

I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:

Write to text file:

$fp = @fopen ("text1.txt", "r");

$fh = @fopen("text2.txt", 'a+');

if ($fp) {
 //for each line in file
    while(!feof($fp)) {
    //push lines into array
    $thisline = fgets($fp);
    $thisline1 = trim($thisline);

     $stringData = $thisline1. "
";
    fwrite($fh, $stringData);

                  fwrite($fh, "test");

                }
            }
fclose($fp);
fclose($fh);

Read from the written textfile

$page = join("",file("text2.txt"));
$kw = explode("
", $page);
for($i=0;$i<count($kw);$i++){

 echo rtrim($kw[$i]);

}

But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.

How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.

Thanks In Advance

  • 写回答

1条回答 默认 最新

  • douzhui1972 2013-01-30 07:47
    关注

    I'm not sure whether you have issues with the even line numbers or with reading the file back in.

    Here is the solution for the even line numbers.

    $page = join("",file("text2.txt"));
    $kw = explode("
    ", $page);
    for($i=0;$i<count($kw);$i++){
    
        $myValue = rtrim($kw[$i]);
        if(i % 2 == 0)
        {
            echo $myValue;
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀