最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】PHP中把字符串文本等数据保存到文件中

PHP crifan 3529浏览 0评论

【问题】

PHP代码,已获得一个字符串变量,是html代码。

想要将其保存到一个文件中,而不是打印出来。

【解决过程】

1.参考:

PHP – File Write: fwrite Function

(and another related link: 

PHP File() Function: File_exists, Fopen, Fwrite, Fclose, Fgets, copy, unlink

)

去写代码:

        $outputFilename = "responseHtml.html";
        $outputFp = fopen($outputFilename, 'w') or die("can't create file".$outputFilename);
        fwrite($outputFp, $response);
        fclose($outputFp);
        printAutoNewline("write to outputfile ".$outputFilename." ok.");

就可以实现,将字符串response保存到文件中了。

2.另外又去参考:

Save a string to a file

去用:

file_put_contents($outputFilename, $response);

去保存数据到文件中,也是可以的。

 

【总结】

对于PHP中,将(文本字符串等)数据,保存到文件,至少有这两种写法:

  • 通用的:
$outputFp = fopen($outputFilename, 'w') or die("can't create file".$outputFilename);
fwrite($outputFp, $dataToOutput);
fclose($outputFp);
  • PHP 5.x中的:
file_put_contents($outputFilename, $dataToOutput);

转载请注明:在路上 » 【已解决】PHP中把字符串文本等数据保存到文件中

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.183 seconds, using 22.02MB memory