将 DBF 转换为 CSV

问题描述 投票:0回答:4

我有许多 DBF 数据库文件,我想将其转换为 CSV。有没有办法在 Linux 或 PHP 中做到这一点?

我找到了一些转换 DBF 的方法,但是它们非常慢。

php csv export-to-csv dbf
4个回答
7
投票

尝试 soffice(LibreOffice):

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

2
投票

将 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 );
}

1
投票

使用@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);
}

0
投票

Linux: $sudo apt-get install libreoffice $libreoffice --headless --convert-to csv FILETOCONVERT.DBF

© www.soinside.com 2019 - 2024. All rights reserved.