<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");  // 建立檔案
$txt = "John Doe\n";
fwrite($myfile, $txt);  // 寫入檔案
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);  // 關閉檔案
?>

--

PHP 寫入檔案有很多種方式, 以下列舉常用的幾種 :

第一種: 寫入資料到檔案

語法: file_put_contents(路徑寫入內容 [,狀態])

其中, 狀態沒有設定, 則寫入內容覆蓋原檔案, 狀態設為 FILE_APPEND, 則寫入內容添加到原檔案後面.

 範例
$fileSize = file_put_contents("myTest.txt", "<Hello World, 歡迎光臨>");
echo "寫入檔案成功, 共有 " . $fileSize . " bytes";

結果顯示 :
寫入檔案成功, 共有 27 bytes

第二種: 傳統寫入資料到檔案

語法: fopen(路徑,[狀態]) + fputs(檔案指標寫入內容) + fclose(檔案指標)

其中, 狀態有 r(讀取), w(寫入), a(連接寫入) 搭配 b(二進位), t(文字)

 範例
$file = fopen("myTest.txt", "w");
$fileSize = fputs( $file, "<Hello World, 歡迎光臨>" );
fclose($file);
echo "寫入檔案成功, 共有 " . $fileSize . " bytes";

結果顯示 :
寫入檔案成功, 共有 27 bytes

以上, 提供參考.

--

轉自 https://www.w3schools.com/php/php_file_create.asp

 https://tomkuo139.blogspot.com/2015/04/php-file-write.html

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()