Home  >  Q&A  >  body text

file - php如何随机输出文件内一行?

我的文件很大,不想全部读取,再随机一行,想通过文件指针随机读取一行?

1273517
12736
1273521
127
127358612735381273538fa
1273606
13
1273636
...
天蓬老师天蓬老师2731 days ago608

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 16:36:07

    现在有一个10G文件,要随机获取其中的一行数据。肯定不能一次把内容全部读取!!!
    因此可以按字节随机读取
    使用函数:
    filesize 获取此文件的总字节
    ftell 当前文件指针位置
    fseek 定位文件指针位置
    fgets 按行读取文件

    实现思路有了吧:
    开始位置可以随机取,即可实现随机读取数据。
    比如总字节100,一行10字节,开始读取字节的位置随机取0~90字节中间的数。
    为了数据的完整性,可以多读几行,那么结束位置就设为:开始位置+行数*每行字节大小
    反正大概那个数就行了
    因为每次读取不可能是一行的头,因为可以多读几行,然后用explode分割成一个数组,抛弃数组首尾,再随机获取其中的一条

    下面这是按字节分页读取文件的内容,可以做个参考

    public static function readFileBySize($file, $currentPage=1, $pageSize=100000)
        {
            $read = "";
            $fileSize = filesize($file);
            $totalPage = ceil($fileSize/$pageSize);
    
            $start = filesize($file) - $currentPage*$pageSize;
            $stop  = filesize($file) - ($currentPage-1)*$pageSize;
    
            $fp = fopen($file, 'r');
            fseek($fp, $start, SEEK_SET);
            while(ftell($fp) < $stop){
                $read .= fgets($fp);
            }
            fclose($fp);
    
            $memory = function_exists('ini_get') ? ini_get("memory_limit"):0;
            $returnData = array(
                "fileSize" => $fileSize,
                "pageSize" => $pageSize,
                "totalPage" => $totalPage,
                "currentPage" => $currentPage,
                "memory" => $memory,
                "data" => $read
            );
            return $returnData;
        }

    reply
    0
  • 迷茫

    迷茫2017-04-10 16:36:07

    文件不大可以直接用file()函数读取一个文件,返回一个数组,数组的每一个元素对应文件的一行.

    <?php
    header('Content-Type: text/plain; charset=utf-8');
    $file = file(__FILE__, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $line = mt_rand(0, count($file)-1);
    print_r($file);
    echo $line.': '.$file[$line];

    文件大的话可以用文件指针.

    <?php
    header('Content-Type: text/plain; charset=utf-8');
    $file = __FILE__;
    $fp = fopen($file, 'r');
    $count = 0;
    while ( !feof($fp) ) {
        $line = fgets($fp);
        echo $count.': '.$line;
        $count++;
    }
    fclose($fp);
    echo "\n";
    $rand = mt_rand(0, $count-1);
    $fp = fopen($file, 'r');
    $count = 0;
    while ( !feof($fp) ) {
        $line = fgets($fp);
        if( $count === $rand ) {
            echo $rand.': '.$line;
            exit();
        }
        $count++;
    }
    fclose($fp);

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 16:36:07

    <?php
    $file_path = 't.txt'; //文件路径
    $s = exec('wc -l '.$file_path);//get lines
    $i = 0;
    $fp = fopen($file_path,'r');
    while ( fgets($fp) !== false) {

    $i++;
    if($i === 4){ // if lines = 4
        echo fgets($fp);
    }

    }

    reply
    0
  • Cancelreply