EoQ_Supporting_Files/getData.php

110 lines
2.9 KiB
PHP

<?php
// Set up constants:
$apiToken="nCqnPnrt9HplICvOWhratTIrwkxqe7pILQ524GJG";
$dataCenter = "fra1"; // Example: "us-east-1"
$surveyId = "SV_3pyZVUNpxXm1PZI"; //Survey ID
$urveyId ="SV_bmiHoSHYWIgGM3I"; //Survey ID
//$surveyId = "SV_bmiHoSHYWIgGM3I"; //Survey ID
// 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"]));
$response = curl_exec($ch);
curl_close($ch);
if (!$response) {
die("Error starting export: " . curl_error($ch));
}
$exportData = json_decode($response, true);
$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.zip", $fileContent);
echo "Survey data has been downloaded successfully!\n";
// Path to the ZIP file
$zipFile = './survey_responses.zip'; // Specify the path to your ZIP file
$extractTo = 'survey_responses.json'; // Specify the folder to extract the contents to
// Create a new ZipArchive object
$zip = new ZipArchive();
// Open the ZIP file
if ($zip->open($zipFile) === TRUE) {
// Extract all the contents to the specified folder
$zip->extractTo($extractTo);
$zip->close(); // Close the ZIP file
echo "ZIP file extracted successfully!";
} else {
echo "Failed to open the ZIP file.";
}
?>