<?php
 
// Step 1: Read the DBF file
 
$dbfFilePath = 'your_dbf_file.dbf';
 
 
if (!file_exists($dbfFilePath)) {
 
    die("DBF file not found: $dbfFilePath");
 
}
 
 
// Step 2: Parse the data from the DBF file
 
$dbfData = [];
 
$dbfFile = fopen($dbfFilePath, 'rb');
 
if ($dbfFile) {
 
    // Read the header
 
    $header = fread($dbfFile, 32);
 
    $recordCount = unpack('V', substr($header, 4, 4))[1];
 
    $headerLength = unpack('v', substr($header, 8, 2))[1];
 
    $recordLength = unpack('v', substr($header, 10, 2))[1];
 
 
    fseek($dbfFile, $headerLength);
 
 
    // Read data records
 
    for ($i = 0; $i < $recordCount; $i++) {
 
        $record = fread($dbfFile, $recordLength);
 
        $recordData = unpack('C*', $record);
 
        $recordArray = [];
 
 
        // Extract field values
 
        foreach ($recordData as $index => $value) {
 
            if ($index % 32 === 0) {
 
                continue; // Skip the deletion flag
 
            }
 
 
            $fieldIndex = intdiv($index - 1, 32);
 
            $fieldValue = trim(chr($value));
 
            $recordArray[$fieldIndex] = $fieldValue;
 
        }
 
 
        $dbfData[] = $recordArray;
 
    }
 
 
    fclose($dbfFile);
 
}
 
 
// Step 3: Create a MySQL database and table
 
$servername = 'localhost';
 
$username = 'your_username';
 
$password = 'your_password';
 
$dbname = 'your_database';
 
 
// Create a connection
 
$conn = new mysqli($servername, $username, $password);
 
 
// Check connection
 
if ($conn->connect_error) {
 
    die("Connection failed: " . $conn->connect_error);
 
}
 
 
// Create the database if it doesn't exist
 
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
 
if ($conn->query($sql) === TRUE) {
 
    echo "Database created successfully<br>";
 
} else {
 
    echo "Error creating database: " . $conn->error;
 
}
 
 
// Select the database
 
$conn->select_db($dbname);
 
 
// Create a table with appropriate columns
 
$sql = "CREATE TABLE IF NOT EXISTS dbf_data (
 
    field1 VARCHAR(255),
 
    field2 VARCHAR(255),
 
    field3 VARCHAR(255),
 
    -- Add more columns as needed
 
)";
 
if ($conn->query($sql) === TRUE) {
 
    echo "Table created successfully<br>";
 
} else {
 
    echo "Error creating table: " . $conn->error;
 
    $conn->close();
 
    exit;
 
}
 
 
// Step 4: Insert data into the MySQL table
 
foreach ($dbfData as $record) {
 
    $field1 = $conn->real_escape_string($record[0]); // Replace '0' with the appropriate column index
 
    $field2 = $conn->real_escape_string($record[1]); // Replace '1' with the appropriate column index
 
    $field3 = $conn->real_escape_string($record[2]); // Replace '2' with the appropriate column index
 
 
    $sql = "INSERT INTO dbf_data (field1, field2, field3) VALUES ('$field1', '$field2', '$field3')";
 
    
 
    if ($conn->query($sql) !== TRUE) {
 
        echo "Error inserting record: " . $conn->error;
 
    }
 
}
 
 
$conn->close();
 
echo "Data conversion and insertion completed.";
 
?>
 
 
 |