rkwadriga/php-filereader

dev-master 2020-09-09 06:48 UTC

This package is auto-updated.

Last update: 2024-09-09 15:26:56 UTC


README

需求

此应用程序模板的最小要求是您的 Web 服务器支持 PHP 7.4.0。

安装

$ composer require rkwadriga/php-filereader:dev-master

支持的格式:csv, sql, txt, log, json, yml, yaml

用法

use rkwadriga\filereader\Factory;

class MyApp
{
    public function myFunction()
    {
        // Create a Factory instance
        $factory = new Factory();
        // Create file reader (in this case .yml file reader)
        $fileReader = $factory->getReader('./config/main.yml');

        // Read file (method "readFile" returns an associative array)
        $data = $fileReader->read();

        // Write file
        $fileReader->write([
            'var1' => 'Value 1',
            'var2' => 'Value 2',
        ]);
    }
}

如果您使用相同的目录处理所有文件,可以将此目录放在 Factory 构造函数中,并使用相对文件路径

$factory = new Factory('./files_dir_path');
$fileReader = $factory->getReader('main.yml');

文件读取器会自动创建文件(如果文件不存在)。如果您不希望这样做,将 "getReader" 方法的第二个参数设置为 false

$fileReader = $factory->getReader('main.yml', false);

在这种情况下,尝试读取不存在的文件时,您将获得 "文件未找到" 异常。

如果您有一些特定的文件扩展名,但可以像允许的扩展名之一那样读取,可以设置读取器工厂的 "extensions map"。

$factory = new Factory(null, [
    'xjson' => 'json',
    'xtxt' => 'txt',
    ...
]);