PHP 파일 쓰기

IT위키

파일 열기[편집 | 원본 편집]

  • 쓰기 모드(w)로 파일을 연다.
  • fopen을 사용한다.
<?php
    $myFile = fopen("testfile.txt", "w") or die("Unable to open file!");
?>

(참고) 파일 열기 모드

  • r : 읽기(read)
  • w : 쓰기(write)
  • a: 추가하기(append)

파일 쓰기[편집 | 원본 편집]

  • fwrite를 이용해 파일을 쓴다.
<?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);
?>
  • 결과는 아래와 같다. (newfile.txt)
John Doe
Jane Doe

파일 닫기[편집 | 원본 편집]

  • fclose로 파일을 닫는다.
  • php 파일이 끝나면 알아서 닫기지만, 다 쓰고 나면 아래와 같이 명시적으로 닫아주는 것이 좋다.
<?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);
?>