如何在PHP中解析一个OFX(版本1.0.2)文件


How to parse a OFX (Version 1.0.2) file in PHP?

我有一个从花旗银行下载的OFX文件,这个文件有一个定义在http://www.ofx.net/DownloadPage/Files/ofx102spec.zip的DTD(文件OFXBANK.DTD), OFX文件似乎是SGML有效的。我正在尝试使用PHP 5.4.13的DomDocument,但我得到几个警告和文件未被解析。我的代码是:

$file = "source/ACCT_013.OFX";
$dtd = "source/ofx102spec/OFXBANK.DTD";
$doc = new DomDocument();
$doc->loadHTMLFile($file);
$doc->schemaValidate($dtd);
$dom->validateOnParse = true;

OFX文件开始为:

OFXHEADER:100
DATA:OFXSGML
VERSION:102
SECURITY:NONE
ENCODING:USASCII
CHARSET:1252
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<DTSERVER>20130331073401
<LANGUAGE>SPA
</SONRS>
</SIGNONMSGSRSV1>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>0
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<STMTRS>
<CURDEF>COP
<BANKACCTFROM> ...

我是开放的安装和使用任何程序在服务器(Centos)从PHP调用。

PD:这门课http://www.phpclasses.org/package/5778-PHP-Parse-and-extract-financial-records-from-OFX-files.html不适合我

首先,即使XML是SGML的子集,有效的SGML文件也不一定是格式良好的XML文件。XML更严格,并没有使用SGML提供的所有特性。

由于DOMDocument是基于XML(而不是SGML)的,因此这并不真正兼容。

在这个问题旁边,请参阅2.2在Ofexfin1.doc中打开金融交换头,它解释了

Open Financial Exchange文件的内容由一组简单的标头和该标头定义的内容组成

及后续:

最后一个标题后面有一个空行。然后(对于OFXSGML类型),sgml可读数据以标记开始。

所以找到第一个空白行,并删除所有直到那里。然后通过先将SGML转换为XML将SGML部分加载到DOMDocument中:

$source = fopen('file.ofx', 'r');
if (!$source) {
    throw new Exception('Unable to open OFX file.');
}
// skip headers of OFX file
$headers = array();
$charsets = array(
    1252 => 'WINDOWS-1251',
);
while(!feof($source)) {
    $line = trim(fgets($source));
    if ($line === '') {
        break;
    }
    list($header, $value) = explode(':', $line, 2);
    $headers[$header] = $value;
}
$buffer = '';
// dead-cheap SGML to XML conversion
// see as well http://www.hanselman.com/blog/PostprocessingAutoClosedSGMLTagsWithTheSGMLReader.aspx
while(!feof($source)) {
    $line = trim(fgets($source));
    if ($line === '') continue;
    $line = iconv($charsets[$headers['CHARSET']], 'UTF-8', $line);
    if (substr($line, -1, 1) !== '>') {
        list($tag) = explode('>', $line, 2);
        $line .= '</' . substr($tag, 1) . '>';
    }
    $buffer .= $line ."'n";
}
// use DOMDocument with non-standard recover mode
$doc = new DOMDocument();
$doc->recover = true;
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$save = libxml_use_internal_errors(true);
$doc->loadXML($buffer);
libxml_use_internal_errors($save);
echo $doc->saveXML();

这个代码示例然后输出以下(重新格式化的)XML,这也表明DOMDocument正确加载了数据:

<?xml version="1.0"?>
<OFX>
  <SIGNONMSGSRSV1>
    <SONRS>
      <STATUS>
        <CODE>0</CODE>
        <SEVERITY>INFO</SEVERITY>
      </STATUS>
      <DTSERVER>20130331073401</DTSERVER>
      <LANGUAGE>SPA</LANGUAGE>
    </SONRS>
  </SIGNONMSGSRSV1>
  <BANKMSGSRSV1>
    <STMTTRNRS>
      <TRNUID>0</TRNUID>
      <STATUS>
        <CODE>0</CODE>
        <SEVERITY>INFO</SEVERITY>
      </STATUS>
      <STMTRS><CURDEF>COP</CURDEF><BANKACCTFROM> ...</BANKACCTFROM>
</STMTRS>
    </STMTTRNRS>
  </BANKMSGSRSV1>
</OFX>

我不知道这是否可以针对DTD进行验证。也许这有用。此外,如果SGML没有在同一行上使用标记的值(每行只需要一个元素),那么这种脆弱的转换将会中断。

最简单的OFX解析成数组,方便访问所有值和事务。

function parseOFX($ofx) {
    $OFXArray=explode("<",$ofx);
    $a=array();
    foreach ($OFXArray as $v) {
        $pair=explode(">",$v);
        if (isset($pair[1])) {
            if ($pair[1]!=NULL) {
                if (isset($a[$pair[0]])) {
                    if (is_array($a[$pair[0]])) {
                        $a[$pair[0]][]=$pair[1];
                    } else {
                        $temp=$a[$pair[0]];
                        $a[$pair[0]]=array();
                        $a[$pair[0]][]=$temp;
                        $a[$pair[0]][]=$pair[1];
                    }
                } else {
                    $a[$pair[0]]=$pair[1];
                }
            }
        }
    }
    return $a;
}

我使用这个:

$source = utf8_encode(file_get_contents('a.ofx'));
//add end tag
$source = preg_replace('#^<([^>]+)>([^'r'n]+)'r?'n#mU', "<$1>$2</$1>'n", $source);
//skip header
$source = substr($source, strpos($source,'<OFX>'));
//convert to array
$xml = simplexml_load_string($source);
$array = json_decode(json_encode($xml),true);
print_r($array);