Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP插入文件_Php - Fatal编程技术网

PHP插入文件

PHP插入文件,php,Php,我必须在特定位置向文件插入文本,而不必读/写整个文件。仅仅使用php就可以吗 mytext.txt content is 123456789 <?php $message='new'; $file='mytext.txt'; $fh = fopen($file, 'rw+'); fseek($fh, 3); fwrite($fh, $message); fclose($fh); ?> mytext.txt的内容是123456789 此代码将在指定位置覆盖。 我要找的是

我必须在特定位置向文件插入文本,而不必读/写整个文件。仅仅使用php就可以吗

mytext.txt content is 123456789

<?php
$message='new';
$file='mytext.txt';
$fh = fopen($file, 'rw+');
fseek($fh, 3);
fwrite($fh, $message);
fclose($fh);
?>     
mytext.txt的内容是123456789
此代码将在指定位置覆盖。
我要找的是“0123new456789”而不是“123new789”

我认为如果不先阅读文件,就不可能完成您想要做的事情。不过,这应该会有所帮助:

// Get file contents
$contents = file_get_contents($file);
// Split your strings
$beginning = substr($contents, 0, 4);
$ending = substr($contents, 4, 6);
// Re-write contents
$contents = $beginning . $message . $end;
// Write file contents
file_put_contents($file, $contents);
谢谢

安德鲁你别无选择。 fopen()始终将指针放在文件的开头或结尾。在任何情况下,你必须通过文件,直到你找到你要找的。你可以在那里关门。 请参阅相关文档


顺便说一下,fseek($fh,3)并不意味着找到3。正在检索长度为3字节的内容。请参见

如果需要写入特定位置,则必须先读取、修改然后写入文件。否。不能拆分为文件的中间部分。您可以fseek/fwrite,但只需覆盖其中的内容。你必须开始一个新文件,复制第一位,输出你的新内容,复制最后一位。嘿!你应该考虑把答案作为最终答案。这将给用户更多的动力在将来回答您的难题。