Hàm parse_ini_file

Hàm parse_ini_file nhận đường dẫn đến file INI làm tham số đầu tiên, cũng như hai tham số không bắt buộc: tham số thứ hai xác định xem có cần xử lý các section hay không, và tham số thứ ba - chế độ quét file.

Cú pháp

phpparse_ini_file(
  string $filename,
  bool $process_sections = false,
  int $scanner_mode = INI_SCANNER_NORMAL
);

Ví dụ

Tạo một file config.ini với nội dung sau:

php; config.ini
database = mysql
host = localhost
user = root
password = 12345

Bây giờ hãy đọc nó:

php<?php
  $res = parse_ini_file('config.ini');
  print_r($res);
?>

Kết quả thực thi mã:

php[
  'database' => 'mysql',
  'host' => 'localhost',
  'user' => 'root',
  'password' => '12345'
]

Ví dụ

Bây giờ thêm các section vào file INI của chúng ta:

php; config.ini
[database]
type = mysql
host = localhost

[credentials]
user = root
password = 12345

Đọc file với việc xử lý các section:

php<?php
  $res = parse_ini_file('config.ini', true);
  print_r($res);
?>

Kết quả thực thi mã:

php[
  'database' => [
    'type' => 'mysql',
    'host' => 'localhost'
  ],
  'credentials' => [
    'user' => 'root',
    'password' => '12345'
  ]
]

Ví dụ

Trình bày cách hoạt động với INI_SCANNER_TYPED:

php; config.ini
debug = true
port = 3306
timeout = 3.5

Đọc file với kiểu hóa giá trị:

php<?php
  $res = parse_ini_file('config.ini', false, INI_SCANNER_TYPED);
  print_r($res);
?>

Kết quả thực thi mã:

php[
  'debug' => true,
  'port' => 3306,
  'timeout' => 3.5
]

Xem thêm

  • hàm file_get_contents,
    hàm đọc file vào một chuỗi
  • hàm file,
    hàm đọc file vào một mảng