我正在创建一个网站。它有这个功能:
public static function createPost($postName,$user,$content) {
echo "Posting...";
$dir = fopen(storage_path('app/posts.xml'), "r+");
$contents = fread($dir,filesize(storage_path('app/posts.xml')));
echo $contents;
$contents = str_replace('</posts>', '', $dir);
fwrite($dir,$contents);
fclose($dir);
$file = fopen(storage_path('app/posts.xml'), "a") or die("<h1>500 Server Error.</h1>");
fwrite($file,"<post>\n");
fwrite($file,'<postname><div id="postname">'.$postName.'</div>
</postname>\n');
fwrite($file,"<div></div>");
fwrite($file,"<user>By ".$user."</user>\n");
fwrite($file,"<div></div>");
fwrite($file,"<content>".$content."</content>\n");
fwrite($file,"</post>\n");
fwrite($file,"</posts>\n");
fclose($file);
echo "<script>window.location.assign('/home.php');</script>";
}
但是,当我运行它时,它并没有取代&#39;&#39; (第6行)。相反,它返回一个奇怪的字符串
资源ID#188
该文件存在。那么为什么会这样呢?
答案 0 :(得分:0)
您正在尝试对此资源执行str_replace(而不是在文本本身上):
$dir = fopen(storage_path('app/posts.xml'), "r+");
根据位于http://php.net/manual/en/function.fopen.php的PHP手册,返回值可以是成功时的文件指针资源,也可以是出错时的FALSE。
尝试用$ content代替$ dir:
$contents = str_replace('</posts>', '', $contents);