用于创建/操作固定宽度文本文件的PHP库

Bry*_*gee 18 php edi text-files fixed-width

我们有一个Web应用程序,可以进行时间跟踪,工资单和人力资源.因此,我们必须编写大量固定宽度的数据文件,以便导出到其他系统(州税申报,ACH文件等).有没有人知道一个好的库,你可以在那里定义记录类型/结构,然后在OOP范例中对它们采取行动?

这个想法将是您处理规范的类,然后使用所述规范的实例.IE:

$icesa_file = new FixedWidthFile();
$icesa_file->setSpecification('icesa.xml');
$icesa_file->addEmployer( $some_data_structure );
Run Code Online (Sandbox Code Playgroud)

其中icesa.xml是包含规范的文件,尽管您可以使用OOP调用自己定义它:

$specification = new FixedWidthFileSpecification('ICESA');
$specification->addRecordType(
    $record_type_name = 'Employer',
    $record_fields = array(
         array('Field Name', Width, Vailditation Type, options)
         )
     );
Run Code Online (Sandbox Code Playgroud)

编辑:我不是在寻找关于如何编写这样一个库的建议 - 我只是想知道一个是否已经存在.谢谢!!

Jak*_*ger 8

我不知道一个库可以完全满足您的需求,但是应该直接推出自己的类来处理这个问题.假设您主要对以这些格式编写数据感兴趣,我会使用以下方法:

(1)为固定宽度字符串编写一个轻量级格式化程序类.它必须支持用户定义的记录类型,并且在允许的格式方面应该是灵活的

(2)为您使用的每种文件格式实例化此类,并添加所需的记录类型

(3)使用此格式化程序格式化数据

如您所建议的那样,您可以在XML中定义记录类型并在步骤(2)中加载此XML文件.我不知道你对XML有多么有经验,但根据我的经验,XML格式经常会引起很多麻烦(可能是由于我自己对XML的无能).如果您只在PHP程序中使用这些类,那么在XML中定义格式并没有什么好处.如果您还需要在许多其他应用程序中使用文件格式定义,则使用XML是一个不错的选择.

为了说明我的想法,以下是我认为您将使用此建议的格式化程序类:

<?php
include 'FixedWidthFormatter.php' // contains the FixedWidthFormatter class
include 'icesa-format-declaration.php' // contains $icesaFormatter
$file = fopen("icesafile.txt", "w");

fputs ($file, $icesaFormatter->formatRecord( 'A-RECORD', array( 
    'year' => 2011, 
    'tein' => '12-3456789-P',
    'tname'=> 'Willie Nelson'
)));
// output: A2011123456789UTAX     Willie Nelson                                     

// etc...

fclose ($file);
?>
Run Code Online (Sandbox Code Playgroud)

该文件icesa-format-declaration.php可能包含格式的声明,如下所示:

<?php
$icesaFormatter = new FixedWidthFormatter();
$icesaFormatter->addRecordType( 'A-RECORD', array(
    // the first field is the record identifier
    // for A records, this is simply the character A
    'record-identifier' => array(
        'value' => 'A',  // constant string
        'length' => 1 // not strictly necessary
                      // used for error checking
    ),
    // the year is a 4 digit field
    // it can simply be formatted printf style
    // sourceField defines which key from the input array is used
    'year' =>  array(
        'format' => '% -4d',  // 4 characters, left justified, space padded
        'length' => 4,
        'sourceField' => 'year'
    ),
    // the EIN is a more complicated field
    // we must strip hyphens and suffixes, so we define
    // a closure that performs this formatting
    'transmitter-ein' => array(
        'formatter'=> function($EIN){
            $cleanedEIN =  preg_replace('/\D+/','',$EIN); // remove anything that's not a digit
            return sprintf('% -9d', $cleanedEIN); // left justified and padded with blanks
        },
        'length' => 9,
        'sourceField' => 'tein'
    ),
    'tax-entity-code' => array(
        'value' => 'UTAX',  // constant string
        'length' => 4
    ),
    'blanks' => array(
        'value' => '     ',  // constant string
        'length' => 5
    ),
    'transmitter-name' =>  array(
        'format' => '% -50s',  // 50 characters, left justified, space padded
        'length' => 50,
        'sourceField' => 'tname'
    ),
    // etc. etc.
));
?>
Run Code Online (Sandbox Code Playgroud)

然后你只需要FixedWidthFormatter类本身,它可能看起来像这样:

<?php

class FixedWidthFormatter {

    var $recordTypes = array();

    function addRecordType( $recordTypeName, $recordTypeDeclaration ){
        // perform some checking to make sure that $recordTypeDeclaration is valid
        $this->recordTypes[$recordTypeName] = $recordTypeDeclaration;
    }

    function formatRecord( $type, $data ) {
        if (!array_key_exists($type, $this->recordTypes)) {
            trigger_error("Undefinded record type: '$type'");
            return "";
        }
        $output = '';
        $typeDeclaration = $this->recordTypes[$type];
        foreach($typeDeclaration as $fieldName => $fieldDeclaration) {
            // there are three possible field variants:
            //  - constant fields
            //  - fields formatted with printf
            //  - fields formatted with a custom function/closure
            if (array_key_exists('value',$fieldDeclaration)) {
                $value = $fieldDeclaration['value'];
            } else if (array_key_exists('format',$fieldDeclaration)) {
                $value = sprintf($fieldDeclaration['format'], $data[$fieldDeclaration['sourceField']]);
            } else if (array_key_exists('formatter',$fieldDeclaration)) {
                $value = $fieldDeclaration['formatter']($data[$fieldDeclaration['sourceField']]);
            } else {
                trigger_error("Invalid field declaration for field '$fieldName' record type '$type'");
                return '';
            }

            // check if the formatted value has the right length
            if (strlen($value)!=$fieldDeclaration['length']) {
                trigger_error("The formatted value '$value' for field '$fieldName' record type '$type' is not of correct length ({$fieldDeclaration['length']}).");
                return '';
            }
            $output .= $value;
        }
        return $output . "\n";
    }
}


?>
Run Code Online (Sandbox Code Playgroud)

如果您还需要读取支持,可以扩展Formatter类以允许读取,但这可能超出了本答案的范围.


A J*_*eek -1

也许 dbase 函数就是您想要使用的。它们不是 OOP,但构建一个能够作用于数据库集中提供的函数的类可能不会太困难。

请查看下面的链接,了解有关 PHP 中可用的 dbase 功能的详细信息。如果您只是想创建一个文件以导入到另一个系统中,那么这些函数应该适合您。只要确保您注意警告即可。一些关键警告是:

  • 不支持索引或备注字段。
  • 不支持锁定。
  • 两个并发的 Web 服务器进程修改同一个 dBase 文件很可能会破坏您的数据库。

http://php.net/manual/en/book.dbase.php