Categories
PHP

PHP에서 텍스트 파일을 한 줄씩 (line by line) 읽기

PHP 에서 텍스트 파일을 라인 (line) 단위로 읽는 방법을 알아보자.

1. fgets() 함수

fgets() 함수는 파일 포인터로부터 하나의 라인을 읽는다. 읽을 데이터가 없을 경우에는 false 를 리턴한다.

텍스트 파일을 읽기 전용 모드로 연다.

$fp = fopen(“xtmci.txt”, “r”);

while 루프와 fgets() 함수로 파일을 읽어보자.

while (($line = fgets($fp)) !== false) {    // 리턴값이 false 가 아닐 경우 계속 읽는다.
  echo $line;    // 읽은 라인을 출력한다. $line 변수에는 개행 문자가 포함되어 있다.
}
  

파일을 닫는다.

fclose($fp);

읽어들인 라인에서 개행 문자를 제거할 때는 rtrim() 함수를 쓴다.

$line = rtrim($line);

2. file() 함수

file() 함수는 파일 전체를 읽어 라인 단위로 배열에 저장한다. 읽기에 실패할 경우에는 false 를 리턴한다.

텍스트 파일을 읽어 배열에 저장해 보자.

$arr_lines = file(“xtmci.txt”);

배열의 각 요소는 텍스트 파일의 각 라인에 대응한다. 읽어들인 개행 문자는 보존된다.

foreach 루프로 배열의 각 요소를 출력한다.

foreach ($arr_lines as $line) {
  echo $line;
}

file() 함수를 쓸 경우에는 별도로 파일을 열고 닫는 작업이 필요없다. 함수 내부에서 자동으로 수행되기 때문이다.

9 replies on “PHP에서 텍스트 파일을 한 줄씩 (line by line) 읽기”

Pretty nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!

Hello outstanding blog! Does running a blog such
as this take a massive amount work? I’ve no expertise in coding but I had been hoping to start my own blog in the near future.
Anyway, should you have any recommendations or techniques for new blog owners please share.

I understand this is off subject however I just wanted to ask.
Appreciate it!

You’re so interesting! I don’t suppose I have read anything like this before.
So wonderful to find another person with a few genuine thoughts on this issue.

Seriously.. many thanks for starting this up.
This website is something that is required on the web, someone with a bit of originality!

You actually make it seem so easy with your presentation but I find this
topic to be actually something which I think I would never
understand. It seems too complex and very broad for me.
I’m looking forward for your next post, I will try to get the hang
of it!

I do not even know how I finished up here, but I assumed
this put up was once great. I do not realize who you are but definitely you are going to
a well-known blogger if you happen to are not already. Cheers!

Hello my family member! I want to say that this article
is amazing, great written and come with almost all vital infos.
I’d like to peer extra posts like this .

Leave a Reply to I Fashion Styles Cancel reply

Your email address will not be published. Required fields are marked *