file_get_contents 和 file_put_contents

  • 387
  • 0
  • PHP
  • 2019-10-05

file_get_contentsfile_put_contents 介紹與範例

 

file_get_contents 可以用來獲取內容,或執行網址,如下範例:

<?php
	$url='http://www.baidu.com/';
	$html=file_get_contents($url);
	echo $html;
?>

 

file_put_contents 可以用來將一段文字寫入文字檔,如下範例:

  • FILE_APPEND 是接續寫入在尾巴的意思。
  • 若要加在前面,可以先使用 file_get_contents 獲取文件內容,再使用 file_put_contents 寫入。
<?php
	file_put_contents("test.txt","一段文字");
	file_put_contents("test.txt","\r\n新的一段文字",FILE_APPEND);
	
	$fname = "test.txt";
	$str = file_get_contents($fname);
	file_put_contents("log.txt","最新的一段文字\r\n".$str);
?>