将DBF转换为CSV

时间:2015-04-09 04:24:10

标签: php csv export-to-csv dbf

我有许多DBF数据库文件,我想将其转换为CSV。有没有办法在Linux或PHP中执行此操作?

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

3 个答案:

答案 0 :(得分:1)

将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 :(得分:1)

尝试soffice(LibreOffice):

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

答案 2 :(得分:0)

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