php中读取文件方法整理

本文深入解析了PHP中处理文件的各种方法,包括file(), file_get_contents(), fopen(), fgets(), fgetss(), fgetc(), fread(), readfile(), fsockopen()和popen()等函数的使用技巧与示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法介绍

  • file() - Reads entire file into an array
  • file_get_contents() - Reads entire file into a string
  • fopen() - Opens file or URL
    • fgets() - Gets line from file pointer
    • fgetss() — Gets line from file pointer and strip HTML tags
    • fgetc() — Gets character from file pointer
    • fread() - Binary-safe file read
  • readfile() - Outputs a file
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer

1、 file() 将整个文件转成数组

用法:file( string $filename[, int $flags = 0[, resource $context]] ) : array  /false
filename:file路径
flags : 可以是一个或者多个FILE_USE_INCLUDE_PATH,FILE_IGNORE_NEW_LINES(omit newline省略换行符),FILE_SKIP_EMPTY_LINES
<?php
$lines = file('http://www.example.com/');
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

$html = implode('', file('http://www.example.com/'));
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?> 

2、file_get_contents 将整个文件转成字符串

用法:file_get_contents( string $filename[, bool $use_include_path = FALSE[, resource $context[, int $offset = 0[, int $maxlen]]]] ) : string  /false
基本上用法跟file一样,多了offset和maxlen option
<?php
$lines = file_get_contents('http://www.example.com/');
$trimmed = file_get_contents('teste.txt');
$trimmed = file_get_contents('teste.txt',FALSE, NULL, 3, 8 );
?> 

3、fopen 打开文件或者url

用法: fopen( string $filename, string $mode[, bool $use_include_path = FALSE[, resource $context]] ) : resource
mode: r(只读),r+(读写),w(只写),w+(读写),a(只写 追加),a+(读写 追加),x(只写 新文件),x+(读写 新文件)
3.1、fgets 从文件指针中获取行
用法:fgets( resource $handle[, int $length] ) : string
$handle:文件指针必须有效,并且必须指向由fopen()或fsockopen()成功打开的文件(但尚未由fclose()关闭)。 
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>
3.2、fgetss 从文件指针获取行并删除HTML标记(strip_tags())
用法: fgetss( resource $handle[, int $length[, string $allowable_tags]] ) : string
<?php
$str = <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);

$handle = @fopen("sample.php", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgetss($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?> 
3.3、fgetc 从文件指针中获取字符
用法: fgetc( resource $handle) : string
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?> 
3.4、fread 二进制安全文件读取 ,读取文件转成字符串
用法:fread( resource $handle, int $length) : string
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
如果所要读取的文件不是本地普通文件,而是远程文件或者流文件,就不能用这种方法,因为,filesize不能获得这些文件的大小。此时,你需要通过feof()或者fread()的返回值判断是否已经读取到了文件的末尾。
<?php
    $handle = fopen('http://www.baidu.com', 'r');
    $content = '';
    while(!feof($handle)){
        $content .= fread($handle, 8080);
    }
    echo $content;
    fclose($handle);
?>

<?php
    $handle = fopen('http://www.baidu.com', 'r');
    $content = '';
    while(false != ($a = fread($handle, 8080))){//返回false表示已经读取到文件末尾
        $content .= $a;
    }
    echo $content;
    fclose($handle);
?>

4、 readfile 输出文件

用法:readfile( string $filename[, bool $use_include_path = FALSE[, resource $context]] ) : int
读入一个文件并写入到输出缓冲。返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。
<?php
 $size = readfile('./file.txt');
 echo $size;
?> 

5、fsockopen 打开一个网络连接或者一个Unix套接字连接

用法:fsockopen( string $hostname[, int $port = -1[, int &$errno[, string &$errstr[, float $timeout = ini_get("default_socket_timeout")]]]] ) : resource
fsockopen()将返回一个文件句柄,之后可以被其他文件类函数调用(例如:fgets(),fgetss(),fwrite(),fclose()还有feof())。如果调用失败,将返回FALSE。 
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?> 

6、popen 打开进程文件指针

用法:popen( string $command, string $mode) : resource 打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。 
返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets(),fgetss() 和 fwrite()。当模式为 'r',返回的文件指针等于命令的 STDOUT,当模式为 'w',返回的文件指针等于命令的 STDIN。 
<?php
error_reporting(E_ALL);
/* 加入重定向以得到标准错误输出 stderr。 */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值