DEV Community

Eko Priyanto
Eko Priyanto

Posted on

Import json to Supabase dengan PHP command line

Image description

<?php
// Supabase API Config
$supabaseUrl = 'https://wekekekekeke.supabase.co';
$supabaseKey = 'endaseendasmuendiasmu';

$table = "bencana";

// Meminta input tahun dari user
if (PHP_SAPI === 'cli') {
    echo "Masukkan tahun: ";
    $tahun = trim(fgets(STDIN));
} else {
    $tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');
}

$filename = "$tahun.json";

// Periksa apakah file JSON ada
if (!file_exists($filename)) {
    die("File $filename tidak ditemukan.\n");
}

// Membaca file JSON
$jsonString = file_get_contents($filename);
$dataArray = json_decode($jsonString, true);

// Pastikan JSON memiliki fitur yang diambil
if (isset($dataArray['features']) && is_array($dataArray['features'])) {
    $allData = [];

    // Loop melalui semua features dan ambil properties-nya
    foreach ($dataArray['features'] as $feature) {
        if (isset($feature['properties'])) {
            $allData[] = $feature['properties'];
        }
    }

    if (!empty($allData)) {
        $batchSize = 100; // Jumlah data per batch
        $totalBatches = ceil(count($allData) / $batchSize); // Hitung total batch

        for ($i = 0; $i < $totalBatches; $i++) {
            // Ambil 100 data per batch
            $batchData = array_slice($allData, $i * $batchSize, $batchSize);

            // Konversi ke JSON untuk dikirim ke Supabase
            $postData = json_encode($batchData);

            // Kirim batch ke Supabase
            $ch = curl_init("$supabaseUrl/rest/v1/$table");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Content-Type: application/json",
                "Authorization: Bearer $supabaseKey",
                "apikey: $supabaseKey",
                "Prefer: resolution=merge-duplicates" // Hindari duplikasi data
            ]);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

            $response = curl_exec($ch);
            curl_close($ch);

            echo "Response: $response \n";
            echo "[".$tahun."] Batch " . ($i + 1) . " dari $totalBatches selesai.\n";
            flush();
        }
        echo "Semua batch telah dikirim ke Supabase.\n";
    } else {
        echo "Tidak ada data yang bisa dimasukkan ke dalam database. \n";
    }
} else {
    echo "Data tidak ditemukan dalam JSON. \n";
}
?>

Enter fullscreen mode Exit fullscreen mode

Tampilannya seperti ini, tinggal masukkan tahun/nama file json dan akan diproses per batch isi 100.
kalau selesai atau error ada peringatannya.

Image description

Top comments (0)