setApplicationName('Google Sheets API PHP Quickstart'); $client->setScopes(array( Google_Service_Slides::PRESENTATIONS, Google_Service_Slides::DRIVE, Google_Service_Slides::DRIVE_FILE) ); //$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY); $client->setAuthConfig('credentials.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent'); $tokenPath = 'token.json'; if (file_exists($tokenPath)) { $accessToken = json_decode(file_get_contents($tokenPath), true); $client->setAccessToken($accessToken); } // If there is no previous token or it's expired. if ($client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("Open the following link in your browser:\n%s\n", $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $client->setAccessToken($accessToken); // Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } } // Save the token to a file. if (!file_exists(dirname($tokenPath))) { mkdir(dirname($tokenPath), 0700, true); } file_put_contents($tokenPath, json_encode($client->getAccessToken())); } return $client; } $xml=simplexml_load_file("http://truehits.net/xml/news_all.xml") or die("Error: Cannot create object"); $day=$xml->attributes()->date; foreach($xml->children() as $datas) { if($datas->url == 'www.thairath.co.th') { $rank=$datas->sort; $ip=$datas->uniqueip; $ss=$datas->uniquesession; $pv=$datas->pageviews; break; } } // Get the API client and construct the service object. $client = getClient(); $service = new Google_Service_Sheets($client); // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit // ที่ต้องแก้ spreadsheetId //$spreadsheetId = 'MUST INSERT'; $range = 'Sheet1!A:E'; $requestBody = new Google_Service_Sheets_ValueRange(); $requestBody->setValues(["values" => ["$day","$rank", "$ip","$ss","$pv"]]); $conf = ["valueInputOption" => "RAW"]; $response= $service->spreadsheets_values->append($spreadsheetId, $range, $requestBody,$conf); echo '
', var_export($response, true), '
', "\n"; ?>