我正在尝试使用将HTML添加到文件中fwrite()
。我的最终目标是让它在文件末尾上方添加15行。这是我到目前为止的内容:
<?php
$file = fopen("index.html", "r+");
// Seek to the end
fseek($file, SEEK_END, 0);
// Get and save that position
$filesize = ftell($file);
// Seek to half the length of the file
fseek($file, SEEK_SET, $filesize + 15);
// Write your data
$main = <<<MAIN
//html goes here
MAIN;
fwrite($file, $main);
// Close the file handler
fclose($file);
?>
这样只会覆盖文件的顶部。谢谢。
由于您使用的是文件大小,因此问题中的示例代码无法基于行运行(除非此处未提及有关应用程序中行定义的假设)。如果要使用行,则需要搜索新的行字符(将每行与下一行分隔)。
如果目标文件不是大文件(因此我们可以将整个文件加载到内存中),则可以使用内置的PHPfile()
将文件的所有行读取到数组中,然后将数据插入第15个元素之后。像这样的东西:
<?php
$lines = file($filename);
$num_lines = count($lines);
if ($num_lines > 15) {
array_splice($lines, $num_lines - 15, 0, array($content));
file_put_contents($filename, implode('', $lines));
} else {
file_put_contents($filename, PHP_EOL . $content, FILE_APPEND);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句