
<?php
// Set up constants:
$apiToken="GZjoFiLmb2j62s8AHmMWKN25BZjGBhsU5ez4cwjn";
//$apiToken="nCqnPnrt9HplICvOWhratTIrwkxqe7pILQ524GJG";
$dataCenter = "fra1"; // Example: "us-east-1"
$surveyId = "SV_cAstEvm4ZrPaqGi"; //Framework
$surveyId = "SV_3pyZVUNpxXm1PZI"; //Template 2nd April
$surveyId ="SV_eKy96PPsL4JVZSC"; //Tullis Russell
//$surveyId = "SV_bmiHoSHYWIgGM3I"; //Survey ID
$surveyId = "SV_bD838sNKZEmi6Tc"; //Template 15 May 2025
$surveyId = "SV_cwKjMqAqGxImjMG"; //

// API endpoint URLs
$exportUrl = "https://$dataCenter.qualtrics.com/API/v3/surveys/$surveyId/export-responses";
$statusUrl = "https://$dataCenter.qualtrics.com/API/v3/surveys/$surveyId/export-responses/";
$fileUrl = "https://$dataCenter.qualtrics.com/API/v3/surveys/$surveyId/export-responses/";

// Step 1: Start Export
$headers = [
    "X-API-TOKEN: $apiToken",
    "Content-Type: application/json"
];

$ch = curl_init($exportUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["format" => "json", "compress" => "false"]));
$response = curl_exec($ch);
curl_close($ch);

if (!$response) {
    die("Error starting export: " . curl_error($ch));
}

$exportData = json_decode($response, true);
echo $response;
$progressId = $exportData['result']['progressId'];

// Step 2: Check Export Status
$status = 'inProgress';
while ($status != 'complete') {
    // Sleep for 5 seconds before checking again
    sleep(5);

    $statusCh = curl_init($statusUrl . $progressId);
    curl_setopt($statusCh, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($statusCh, CURLOPT_HTTPHEADER, $headers);
    $statusResponse = curl_exec($statusCh);
    curl_close($statusCh);

    if (!$statusResponse) {
        die("Error checking status: " . curl_error($statusCh));
    }

    //print_r(json_decode($statusResponse, true));
    //exit(0);

    $statusData = json_decode($statusResponse, true);
    $status = $statusData['result']['status'];

    if ($status == 'failed') {
        die("Export failed!");
    }

    echo "Waiting for export to complete... Status: $status\n";
}

// Step 3: Download the Exported File
$fileId = $statusData['result']['fileId'];

$fileCh = curl_init($fileUrl . $fileId . '/file');
curl_setopt($fileCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($fileCh, CURLOPT_HTTPHEADER, $headers);
$fileContent = curl_exec($fileCh);
curl_close($fileCh);

if (!$fileContent) {
    die("Error downloading the file: " . curl_error($fileCh));
}

// Save the file locally
file_put_contents("survey_responses.json", $fileContent);

echo "Survey data has been downloaded successfully!\n";

// No need to create a new ZipArchive object as imported without compression
 






?>



