傅令江的光影色彩世界
PHP读本地文件指定某行内容
2022-10-14 傅令江
<?php
$a = file('xiaohana.txt'); //读取同目录xiaohana.txt文本
echo $a[5];//输入本文档的第6行内容

?>


如果文件较大,内容较多用以下代码


<?php
$c = getLine('./a.txt', 10); // 读取a.txt文件第11行内容
echo $c;
/**
 * 获取指定行内容
 *
 * @param $file 文件路径
 * @param $line 行数
 * @param $length 指定行返回内容长度
 */
function getLine($file, $line, $length = 4096)
{
    $returnTxt = null; // 初始化返回
    $i = 1; // 行数

    $handle = @fopen($file, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, $length);
            if ($line == $i) $returnTxt = $buffer;
            $i++;
        }
        fclose($handle);
    }
    return $returnTxt;
}
?>

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容