Advertisement
Guest User

googlesheetsToPHP

a guest
Jul 24th, 2024
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.79 KB | None | 0 0
  1. <?php
  2.  
  3. require_once __DIR__ . '/vendor/autoload.php';
  4.  
  5. // Google Sheets setup
  6. $client = new \Google_Client();
  7. $client->setApplicationName('Google Sheets with PHP');
  8. $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
  9. $client->setAccessType('offline');
  10. $client->setAuthConfig(__DIR__ . '/credentials.json');
  11.  
  12. $service = new \Google_Service_Sheets($client); // create new instance, allows interaction
  13. $spreadsheetId = "testing123";
  14.  
  15. // Database connection
  16. $host = getenv('DB_HOST') ?: '123';
  17. $port = getenv('DB_PORT') ?: '3306';
  18. $username = getenv('DB_USER') ?: 'testing';
  19. $password = getenv('DB_PASS') ?: 'testing';
  20. $database = getenv('DB_NAME') ?: 'db_testing';
  21.  
  22. try {
  23. // Connect to the database
  24. $pdo = new PDO("mysql:host=$host;port=$port;dbname=$database", $username, $password);
  25. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  26.  
  27. // Get the table name
  28. $tableName = 'acc_ms'; // CHANGE THIS
  29.  
  30. // Fetch data from the database
  31. $stmt = $pdo->query("SELECT * FROM $tableName");
  32. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  33.  
  34. // check for encoding issues
  35. foreach($data as $index => $row) {
  36. foreach($row as $key => $value) {
  37. $data[$index][$key] = utf8_encode($value);
  38. }
  39. }
  40.  
  41. if (empty($data)) {
  42. echo "No data found in the table.";
  43. exit;
  44. }
  45.  
  46. // Prepare data for Google Sheets
  47. if(!empty($data)) {
  48. $values = [];
  49. $headers = array_keys($data[0]);
  50. $values[] = $headers;
  51.  
  52. foreach ($data as $row) {
  53. $rowData = [];
  54. foreach ($headers as $header) {
  55. $rowData[] = ($row[$header] === null) ? '' : (string)$row[$header];
  56. }
  57. $values[] = $rowData;
  58. }
  59. } else {
  60. echo "No data to write.";
  61. }
  62. // Debugging: Print the data fetched from the database
  63. echo "<pre>";
  64. print_r($data);
  65. echo "</pre>";
  66. // Check if a sheet with the table name already exists
  67. $spreadsheet = $service->spreadsheets->get($spreadsheetId);
  68. $sheets = $spreadsheet->getSheets();
  69. $sheetExists = false;
  70. foreach ($sheets as $sheet) {
  71. if ($sheet->getProperties()->getTitle() === $tableName) {
  72. $sheetExists = true;
  73. break;
  74. }
  75. }
  76.  
  77. if (!$sheetExists) {
  78. // Create a new sheet with the table name
  79. $requests = [
  80. new Google_Service_Sheets_Request([
  81. 'addSheet' => [
  82. 'properties' => [
  83. 'title' => $tableName
  84. ]
  85. ]
  86. ])
  87. ];
  88.  
  89. $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
  90. 'requests' => $requests
  91. ]);
  92.  
  93. $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
  94. }
  95. // Debugging: Print the values prepared for Google Sheets
  96. echo "<pre>";
  97. print_r($values);
  98. echo "</pre>";
  99. if (!empty($values)) {
  100. // Prepare the request to update Google Sheets
  101. $body = new Google_Service_Sheets_ValueRange([
  102. 'values' => $values
  103. ]);
  104. $params = [
  105. 'valueInputOption' => 'RAW'
  106. ];
  107.  
  108. // Update the sheet
  109. $range = $tableName . '!A1';
  110. $result = $service->spreadsheets_values->update($spreadsheetId, $range, $body, $params);
  111.  
  112. printf("Sheet '%s' updated with %d cells.", $tableName, $result->getUpdatedCells());
  113. } else {
  114. echo "No data to write.";
  115. }
  116.  
  117. } catch(PDOException $e) {
  118. echo "Database connection failed: " . $e->getMessage();
  119. } catch(Exception $e) {
  120. echo "Error: " . $e->getMessage();
  121. if ($e instanceof Google_Service_Exception) {
  122. print_r($e->getErrors());
  123. }
  124. }
  125.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement