fgets()
是 PHP 中的一个函数,用于从文件指针中读取一行数据。它读取到换行符(\n
)或文件末尾(EOF)为止,并将读取的内容作为字符串返回。
fgets()
函数的使用非常简单,只需提供文件指针即可。fgets()
函数本身没有类型之分,但返回的是一个字符串。
fgets()
读取用户输入。fgets()
函数读取文件时出现乱码,通常是由于文件编码和 PHP 脚本编码不一致导致的。常见的原因包括:
以下是一个示例代码,展示如何去除 BOM 头并读取文件内容:
<?php
function removeBOM($file) {
$bom = "\xEF\xBB\xBF";
$content = file_get_contents($file);
if (substr($content, 0, 3) == $bom) {
$content = substr($content, 3);
}
return $content;
}
$file = 'example.txt';
$content = removeBOM($file);
$handle = fopen($file, 'r');
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
?>
通过以上方法,可以有效解决 fgets()
函数读取文件时出现的乱码问题。
领取专属 10元无门槛券
手把手带您无忧上云