php操作文件的2个基本函数

  • file_get_contents() 将文件读入字符串
  • file_put_contents() 将字符串写入文件

如果是把 字符串保存到文件中,例如 css,js,html,php中,则可以直接保存例如

<?php

//把php字符串写入到 文件中(txt,html,php,js,css中)
$dir = dirname(__FILE__);  //当前路径

$str_txt = "我是txt内容123";
$str_html = '<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello</title> </head> <body> <h1>hello中文</h1> </body> </html>';
$str_php = "<?php echo 'hello'; ?>";
$str_js = "alert('123');";
$str_css = '
*{margin:0;padding:0;font-family:"Microsoft YaHei";-webkit-box-sizing:border-box;box-sizing:border-box;}
.indexbox{height:auto;overflow:hidden;position:relative;padding - bottom:100 px;max - width:640 px;margin:auto;}
.indexbanner{height:auto;}
.swiper - wrapper img{display:block;width:100 %;}
img{border:0;max-width:100%;}
html{background-color:rgb(248,236,214);}
body{width:100%;max-width:640px;min-height:10rem;margin:0 auto!important;background:#fff;box-shadow:0 0 20px #d08b0e;position: relative;}
.zfont0{font-size:0;}
.clear{clear:both;overflow:hidden;}
.zblock{display:block;}
.zflexa{display:-webkit-flex;overflow:hidden;-webkit-justify-content:space-around;-webkit-align-items:center;}
.zflexb{display:-webkit-flex;overflow:hidden;-webkit-justify-content:space-between;-webkit-align-items:center;}
.zflexw{display:-webkit-flex;-webkit-align-items:center;-webkit-flex-wrap:wrap;}
.fzx{height:10px;margin-top:20px;background:#eee;font-size:0;clear:both;}
';


$save_dir_txt = "{$dir}/mytxt.txt";
file_put_contents($save_dir_txt, $str_txt);


$save_dir_html = "{$dir}/mytxt.html";
file_put_contents($save_dir_html, $str_html);


$save_dir_js = "{$dir}/mytxt.js";
file_put_contents($save_dir_js, $str_js);


$save_dir_css = "{$dir}/mytxt.css";
file_put_contents($save_dir_css, $str_css);

再次执行,会覆盖之前的文件。

 

但是如果是图片,用上面的方式会失败。我们先要把图片保存到 字符串中,再取出来保存到文件中。如下

<?php

$dir = dirname(__FILE__);  //当前路径


//把图片保存下来,和上面一样的保存方式,会失败
//我们先把图片存到字符串中,然后再保存到文章中,成功
$str_img = "http://vip.szjs2016.com/static/image/wechat.png";
$save_dir_img = "{$dir}/mytxt.png";
file_put_contents($save_dir_img, file_get_contents($str_img));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值