Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

ฟังก์ชัน file() ใน PHP

ฟังก์ชัน file() ใช้อ่านไฟล์เข้าไปในอาร์เรย์ (array)

Syntax

file(file_path, flag, context)

Parameters

  • file_path − พาธของไฟล์

  • flag − พารามิเตอร์ flags เพิ่มเติม (optional) สามารถเป็นหนึ่งหรือมากกว่าค่าต่อไปนี้:

    • FILE_USE_INCLUDE_PATH − ค้นหาไฟล์ใน include_path

    • FILE_IGNORE_NEW_LINES − ไม่เพิ่ม newline ท้ายแต่ละ element ของ array

    • FILE_SKIP_EMPTY_LINES − ข้ามบรรทัดว่าง

    • FILE_TEXT − เนื้อหาคืนค่าเป็น UTF-8 (PHP 6+)

    • FILE_BINARY − อ่านเป็นข้อมูลไบนารี (ค่าเริ่มต้น) (PHP 6+)

  • context − ปรับพฤติกรรมของสตรีม

Return

ฟังก์ชัน file() คืนค่าไฟล์ในรูปแบบ array มิฉะนั้น false เมื่อล้มเหลว

ตัวอย่าง

สมมติมีไฟล์ "continents.txt" เนื้อหาดังนี้:

The Earth has seven continents. The continents are: Asia, Africa, North America, South America, Antarctica, Europe, and Australia. Asia is the largest in area. Australia is the smallest in terms of area.

โค้ดตัวอย่าง

<?php 
   print_r(file("continents.txt")); 
?>

ผลลัพธ์

Array ( 
   [0] => The Earth has seven continents. 
   [1] => The continents are: Asia, Africa, North America, South America, Antarctica, Europe, and Australia. 
   [2] => Asia is the largest in area. 
   [3] => Australia is the smallest in terms of area. 
)