将DBF转换为CSV

ma8fv8wu  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(76)

我有一些DBF数据库文件,我想转换为CSV。有没有办法在Linux或PHP中做到这一点?
我已经找到了一些方法来转换DBF,但它们非常慢。

5uzkadbs

5uzkadbs1#

试用soffice(LibreOffice):

$ soffice --headless --convert-to csv FILETOCONVERT.DBF
8i9zcol2

8i9zcol22#

将files变量更改为DBF文件的路径。确保文件扩展名与文件的大小写匹配。

set_time_limit( 24192000 );
ini_set( 'memory_limit', '-1' );

$files = glob( '/path/to/*.DBF' );
foreach( $files as $file )
{
    echo "Processing: $file\n";
    $fileParts = explode( '/', $file );
    $endPart = $fileParts[key( array_slice( $fileParts, -1, 1, true ) )];
    $csvFile = preg_replace( '~\.[a-z]+$~i', '.csv', $endPart );

    if( !$dbf = dbase_open( $file, 0 ) ) die( "Could not connect to: $file" );
    $num_rec = dbase_numrecords( $dbf );
    $num_fields = dbase_numfields( $dbf );

    $fields = array();
    $out = '';

    for( $i = 1; $i <= $num_rec; $i++ )
    {
        $row = @dbase_get_record_with_names( $dbf, $i );
        $firstKey = key( array_slice( $row, 0, 1, true ) );
        foreach( $row as $key => $val )
        {
            if( $key == 'deleted' ) continue;
            if( $firstKey != $key ) $out .= ';';
            $out .= trim( $val );
        }
        $out .= "\n";
    }

    file_put_contents( $csvFile, $out );
}
of1yzvn4

of1yzvn43#

使用@Kohjah的代码,这里使用更好的(恕我直言)fputcsv方法更新代码:

// needs dbase php extension (http://php.net/manual/en/book.dbase.php)

function dbfToCsv($file) 
{
    $output_path = 'output' . DIRECTORY_SEPARATOR . 'path';
    $path_parts = pathinfo($file);
    $csvFile = path_parts['filename'] . '.csv';
    $output_path_file = $output_path . DIRECTORY_SEPARATOR . $csvFile;

    if (!$dbf = dbase_open( $file, 0 )) {
        return false;
    }

    $num_rec = dbase_numrecords( $dbf );

    $fp = fopen($output_path_file, 'w');
    for( $i = 1; $i <= $num_rec; $i++ ) {
        $row = dbase_get_record_with_names( $dbf, $i );
        if ($i == 1) {
            //print header
            fputcsv($fp, array_keys($row));
        }
        fputcsv($fp, $row);
    }
    fclose($fp);
}

相关问题