PHP - File |
|
Written by admin
Sunday, 22 August 2010 15:10
|
||||||||||||||||||
|
ตัวอย่างโปรแกรมภาษา PHP การเรียกใช้ ฟังก์ชั่นเกี่ยวกับไฟล์ (File) <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> เราสามารถเปิดไฟล์ได้หลายโหมดดังต่อไปนี้
<html> <body> <?php $file=fopen("bangoi.txt","r") or exit("ไม่สามารถเปิดไฟล์นี้ได้!"); ?> </body> </html> ตัวอย่างโค้ด การปิดไฟล์ Code: <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?> การตรวจสอบ จุดสิ้นสุดของไฟล์ (End-of-File) if (feof($file)) echo "End of file"; ตัวอย่างโค้ด การอ่านไฟล์ ทีละบรรทัด โดยตรวจสอบจุดสิ้นสุดของไฟล์ End-of-File ด้วย ถ้าถึงจุดสิ้นสุดของไฟล์แล้ว ใช้คำสั่ง ปิดไฟล์ fclose(); Code: <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?> ตัวอย่างโค้ด การอ่านทีละตัวอักษร โดยตรวจสอบจุดสิ้นสุดของไฟล์ End-of-File ด้วย ถ้าถึงจุดสิ้นสุดของไฟล์แล้ว ใช้คำสั่ง ปิดไฟล์ fclose(); Code: <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?> |