V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yumijie
V2EX  ›  PHP

PHP 读写字符串到.TXT 文件中怎么不对啊,请帮忙看看

  •  
  •   yumijie · 2016-02-24 13:37:48 +08:00 · 1876 次点击
    这是一个创建于 2985 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码如下:
    <!doctype html>
    <html>
    <head>
    <title>四位.club 域名</title>
    <meta charset="utf-8">
    </head>
    <body>
    <?php
    /*
    test.txt 文件内容为:

    10ferents.club
    1901.club
    1992.club
    288cash.club
    2nd.club
    365gold.club
    3dscanning.club
    406disco.club
    99fitness.club
    abuo9i8n3.club
    abuo9i8n5.club
    abur5t6b2.club
    abut6y7n1.club
    abut6y7n4.club
    abut6y7n7.club
    abuy7u8n6.club
    1234.club
    abcd.club


    4.txt 只有:
    abcd.club

    正确的答案应该是:
    1901.club
    1992.club
    1234.club
    abcd.club
    */
    $handle=fopen("test.txt","r");
    while(!feof($handle)){
    $str=fgets($handle);
    if(stripos($str,".")==4){
    file_put_contents("4.txt",$str);
    }
    }
    ?>
    </select><BR>
    </body>
    </html>
    筛选域名用的,但是结果怎么只显示一行啊,用
    echo $str."<br>\n";显示结果在正常的.
    4 条回复    2016-02-24 13:58:07 +08:00
    zgk
        1
    zgk  
       2016-02-24 13:49:21 +08:00 via Android   ❤️ 1
    因为 file_put_contents 写入文件时是覆盖原本内容的,所以程序运行完只剩下最后那一个
    coseylee
        2
    coseylee  
       2016-02-24 13:52:47 +08:00   ❤️ 2
    file_put_contents 增加第三个参数 FILE_APPEND 。
    yumijie
        3
    yumijie  
    OP
       2016-02-24 13:55:14 +08:00
    @coseylee 是的,只要把 file_put_contents("4.txt",$str); 修改为: file_put_contents("4.txt",$str,FILE_APPEND);就好了。
    zgk
        4
    zgk  
       2016-02-24 13:58:07 +08:00 via Android   ❤️ 1
    应该是默认覆盖原本内容,没注意到还有第三个参数=_=
    http://php.net/manual/zh/function.file-put-contents.php
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1249 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:47 · PVG 07:47 · LAX 16:47 · JFK 19:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.