doufuxing8562 2019-02-14 18:18
浏览 113
已采纳

从PHP写入html中的特定行

I'm new to php. The thing I'm trying to accomplish here is to see what is the number of the last line in my html document (1,2,3...) and put that value into a variable and write

Hello world

to the html document but 2 or 3 lines above the last line. So right above the body close tag. I have been trying for days now and nothing seems to work.

sampletext.html

    <html>
<head>
     <title>WEB</title>
   </head>
 <body>
   <p>WEB test 335</p>
 </body>
    </html>

This one doesn't output:

<?php
$file = new SplFileObject('sampletext.html');
$file->seek(3);     // Seek to line no. 4
echo $file->current(); // Print contents of that line
?>

I also tried this one ,but it only writes at the end of the file:

<?php
 $file = fopen("sampletext.html","a");  //I also tried w,a+,r,r+ 
 $txt = "Hello world";
 fseek(fp, 0, SEEK_END);
 fwrite($file, $txt);
 fclose($file);
 ?>

There are a more but I can't seem to find them in my testing folder. I have read somewhere that it's possible to move the last few lines into temp memory and fwrite something and then move the lines from temp memory back into the file.

As I mentioned before I am very new to php and don't fully understand it yet!

  • 写回答

3条回答 默认 最新

  • dqp4933 2019-03-09 22:52
    关注

    The only thing that I found that works is to delete the last few lines of the code, write what you wanted and then write the code you deleted or use a php function that reads through the file and looks for a specific code (variable or something else but it shouldn't repeat in that context) and change it with another bit of code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵