这是控制器的代码
<?php
class Creplace extends Controller {
        function Creplace()
    {
        parent::Controller();    
    } function Replace()
 {
//***********************打开文件*******************************************
 $filename=getcwd()."\\system\\application\\controllers\\Vindex.html";
if(!file_exists($filename)){
    $fp=fopen($filename,"w");
    fclose($fp);
}
readfile($filename);
//$fp=fopen($filename,"r");
//***********************替换文件********************************************
  define("NL","<br/>\n");
  $str1="<title>我是中国人</title>";
$str2="<body>我们都是中国人</body>";
//print htmlspecialchars($content).NL;//***********************保存文件*************************************
    $f_1=fopen($filename,"r");
    $filename1=getcwd()."\\system\\application\\controllers\\Vindex1.html";
$f_2=fopen($filename1,"w");
while(!feof($f_1))
     { //copy($filename,$filename1);
      $title=fgets($f_1);
      $title=str_replace("我是中国人","你好吗",$str1);
     //fseek($f_2,-10,SEEK_END);
     //fseek($f_2,"5");
      
      fwrite($f_2,$title);
      //copy($filename,$filename1);
      $content=fgets($f_1);
      $content=str_replace("我们都是中国人","大家都很好",$str2);
      //fseek($f_2,-5,SEEK_END);
      //fseek($f_2,"10");
      
       fwrite($f_2,$content);
     
     }
fclose($f_1);
fclose($f_2); }
}
?>
这是原html(Vindex.html)的代码
<html><head><title>我是中国人</title></head><body>我们都是中国人</body></html>我测试了是可以实现替换的。但是师兄说我没有保存文件。我是另建一个文件,把替换后的内容写进去的。大家觉得可以吗??我百度了下,也不知道怎么用PHP来保存文件,请大家帮帮忙,谢谢了。

解决方案 »

  1.   

    可以删除原文件,新文件改名
    //fseek($f_2,-5,SEEK_END);
      //fseek($f_2,"10");
       
      fwrite($f_2,$content);  unlink($filename);
      rename($filename1,$filename);  }
      

  2.   

    位置错了,放到while循环外面!
      

  3.   

    我测试了你写的两个语句,有错误哦,不行哦。
    A PHP Error was encounteredSeverity: WarningMessage: unlink() expects parameter 1 to be string, resource givenFilename: controllers/Cindex.phpLine Number: 43
    A PHP Error was encounteredSeverity: WarningMessage: rename() expects parameter 1 to be string, resource givenFilename: controllers/Cindex.phpLine Number: 44