<?php
/*
https://www.nidup.io/blog/manipulate-google-sheets-in-php-with-api
*/
require './vendor/autoload.php';
// configure the Google Client
$client = new \Google_Client();
$client->setApplicationName('Google Sheets API');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
// credentials.json is the key file we downloaded while setting up our Google Sheets API
$path = '***'; //google console admin need to generate this file
$client->setAuthConfig($path);
// configure the Sheets Service
$service = new \Google_Service_Sheets($client);
$spreadsheetId = '***'; // get with share with and see to url
// the spreadsheet id can be found in the url https://docs.google.com/spreadsheets/d/143xVs9lPopFSF4eJQWloDYAndMor/edit
$spreadsheet = $service->spreadsheets->get($spreadsheetId);
var_dump($spreadsheet);
// all values
$range = 'List 1'; // here we use the name of the Sheet to get all the rows
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
var_dump($values);
// rows by range
$range = 'List 1!A1:F10';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
var_dump($values);
// cells of column
$range = 'List1!B1:B21'; // the column containing the movie title
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
var_dump($values);
// rows into json objects
$range = 'Sheet1';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$rows = $response->getValues();
// Remove the first one that contains headers
$headers = array_shift($rows);
// Combine the headers with each following row
$array = [];
foreach ($rows as $row) {
$array[] = array_combine($headers, $row);
}
var_dump($array);
/*
$jsonString = json_encode($array, JSON_PRETTY_PRINT);
print($jsonString);
*/
// append new row
$newRow = [
'456740',
'Hellboy',
'https://image.tmdb.org/t/p/w500/bk8LyaMqUtaQ9hUShuvFznQYQKR.jpg',
"Hellboy comes to England, where he must defeat Nimue, Merlin's consort and the Blood Queen. But their battle will bring about the end of the world, a fate he desperately tries to turn away.",
'1554944400',
'Fantasy, Action'
];
$rows = [$newRow]; // you can append several rows at once
$valueRange = new \Google_Service_Sheets_ValueRange();
$valueRange->setValues($rows);
$range = 'List 1'; // the service will detect the last row of this sheet
$options = ['valueInputOption' => 'USER_ENTERED'];
$service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $options);
// update existing
$updateRow = [
'456740',
'Hellboy Updated Row',
'https://image.tmdb.org/t/p/w500/bk8LyaMqUtaQ9hUShuvFznQYQKR.jpg',
"Hellboy comes to England, where he must defeat Nimue, Merlin's consort and the Blood Queen. But their battle will bring about the end of the world, a fate he desperately tries to turn away.",
'1554944400',
'Fantasy, Action'
];
$rows = [$updateRow];
$valueRange = new \Google_Service_Sheets_ValueRange();
$valueRange->setValues($rows);
$range = 'Sheet1!A2'; // where the replacement will start, here, first column and second line
$options = ['valueInputOption' => 'USER_ENTERED'];
$service->spreadsheets_values->update($spreadsheetId, $range, $valueRange, $options);
// delete some row
$range = 'Sheet1!A23:F24'; // the range to clear, the 23th and 24th lines
$clear = new \Google_Service_Sheets_ClearValuesRequest();
$service->spreadsheets_values->clear($spreadsheetId, $range, $clear);
/** with text formatting */
$range = 'List 1!B4';
$params = [
'ranges' => $range,
'fields' => 'sheets.data.rowData.values',
'includeGridData' => true,
];
$response = $service->spreadsheets->get($spreadsheetId, $params);
$data = $response->getSheets()[0]['data'][0]['rowData'][0]['values'][0];
$formattedValue = $data['formattedValue'];
$hyperlink = $data['hyperlink'];
$userEnteredFormat = $data['userEnteredFormat'];
var_dump($formattedValue);
var_dump($hyperlink);
var_dump($userEnteredFormat);
<?php
/* https://betterprogramming.pub/how-to-make-your-php-code-beautiful-with-chainable-methods-83d8832b1b16 */
class Collection
{
private $array;
public function __construct($array)
{
$this->array = $array;
}
public function filter($callback)
{
$this->array = array_filter($this->array, $callback);
return $this;
}
public function map($callback)
{
$this->array = array_map($callback, $this->array);
return $this;
}
public function sort($callback)
{
usort($this->array, $callback);
return $this;
}
public function execute()
{
return $this->array;
}
}
$characters = new Collection([
'Maggie Simpson',
'Edna Krabappel',
'Marge Simpson',
'Lisa Simpson',
'Moe Szyslak',
'Waylon Smithers',
'Homer Simpson',
'Bart Simpson'
]);
$simpsons = $characters
->filter(function ($character) {
return preg_match('/^.+\sSimpson$/', $character);
})
->map(function ($character) {
return str_replace(' Simpson', '', $character);
})
->sort(function ($a, $b) {
return strcasecmp($a, $b);
})
->execute();
var_dump($simpsons); // ['Bart', 'Homer', 'Lisa', 'Maggie', 'Marge']
<?php
function getNestedValue($array, $path, $separator = '.') {
$keys = explode($separator, $path);
foreach ($keys as $key) {
if (isset($array[$key])) {
$array = $array[$key];
} else {
return null; // nebo hodnotu podle vašich potřeb
}
}
return $array;
}
$x = [
'a' => [
'b' => [
'c' => 'FINAL C ... ;)'
],
],
];
echo getNestedValue($x, 'a.b.c');
<?php
/**
* Simple FTP Class
*
* @package SFTP
* @name SFTP
* @version 1.0
* @author Shay Anderson 05.11
* @link shayanderson.com
* @license http://www.gnu.org/licenses/gpl.html GPL License
* SFTP is free software and is distributed WITHOUT ANY WARRANTY
*/
final class SFTP {
/**
* FTP host
*
* @var string $_host
*/
private $_host;
/**
* FTP port
*
* @var int $_port
*/
private $_port = 21;
/**
* FTP password
*
* @var string $_pwd
*/
private $_pwd;
/**
* FTP stream
*
* @var resource $_id
*/
private $_stream;
/**
* FTP timeout
*
* @var int $_timeout
*/
private $_timeout = 90;
/**
* FTP user
*
* @var string $_user
*/
private $_user;
/**
* Last error
*
* @var string $error
*/
public $error;
/**
* FTP passive mode flag
*
* @var bool $passive
*/
public $passive = false;
/**
* SSL-FTP connection flag
*
* @var bool $ssl
*/
public $ssl = false;
/**
* System type of FTP server
*
* @var string $system_type
*/
public $system_type;
/**
* Initialize connection params
*
* @param string $host
* @param string $user
* @param string $password
* @param int $port
* @param int $timeout (seconds)
*/
public function __construct($host = null, $user = null, $password = null, $port = 21, $timeout = 90) {
$this->_host = $host;
$this->_user = $user;
$this->_pwd = $password;
$this->_port = (int)$port;
$this->_timeout = (int)$timeout;
}
/**
* Auto close connection
*/
public function __destruct() {
$this->close();
}
/**
* Change currect directory on FTP server
*
* @param string $directory
* @return bool
*/
public function cd($directory = null) {
// attempt to change directory
if(ftp_chdir($this->_stream, $directory)) {
// success
return true;
// fail
} else {
$this->error = "Failed to change directory to \"{$directory}\"";
return false;
}
}
/**
* Set file permissions
*
* @param int $permissions (ex: 0644)
* @param string $remote_file
* @return false
*/
public function chmod($permissions = 0, $remote_file = null) {
// attempt chmod
if(ftp_chmod($this->_stream, $permissions, $remote_file)) {
// success
return true;
// failed
} else {
$this->error = "Failed to set file permissions for \"{$remote_file}\"";
return false;
}
}
/**
* Close FTP connection
*/
public function close() {
// check for valid FTP stream
if($this->_stream) {
// close FTP connection
ftp_close($this->_stream);
// reset stream
$this->_stream = false;
}
}
/**
* Connect to FTP server
*
* @return bool
*/
public function connect() {
// check if non-SSL connection
if(!$this->ssl) {
// attempt connection
if(!$this->_stream = ftp_connect($this->_host, $this->_port, $this->_timeout)) {
// set last error
$this->error = "Failed to connect to {$this->_host}";
return false;
}
// SSL connection
} elseif(function_exists("ftp_ssl_connect")) {
// attempt SSL connection
if(!$this->_stream = ftp_ssl_connect($this->_host, $this->_port, $this->_timeout)) {
// set last error
$this->error = "Failed to connect to {$this->_host} (SSL connection)";
return false;
}
// invalid connection type
} else {
$this->error = "Failed to connect to {$this->_host} (invalid connection type)";
return false;
}
// attempt login
if(ftp_login($this->_stream, $this->_user, $this->_pwd)) {
// set passive mode
ftp_pasv($this->_stream, (bool)$this->passive);
// set system type
$this->system_type = ftp_systype($this->_stream);
// connection successful
return true;
// login failed
} else {
$this->error = "Failed to connect to {$this->_host} (login failed)";
return false;
}
}
/**
* Delete file on FTP server
*
* @param string $remote_file
* @return bool
*/
public function delete($remote_file = null) {
// attempt to delete file
if(ftp_delete($this->_stream, $remote_file)) {
// success
return true;
// fail
} else {
$this->error = "Failed to delete file \"{$remote_file}\"";
return false;
}
}
/**
* Download file from server
*
* @param string $remote_file
* @param string $local_file
* @param int $mode
* @return bool
*/
public function get($remote_file = null, $local_file = null, $mode = FTP_ASCII) {
// attempt download
if(ftp_get($this->_stream, $local_file, $remote_file, $mode)) {
// success
return true;
// download failed
} else {
$this->error = "Failed to download file \"{$remote_file}\"";
return false;
}
}
/**
* Get list of files/directories in directory
*
* @param string $directory
* @return array
*/
public function ls($directory = null) {
$list = array();
// attempt to get list
if($list = ftp_nlist($this->_stream, $directory)) {
// success
return $list;
// fail
} else {
$this->error = "Failed to get directory list";
return array();
}
}
/**
* Create directory on FTP server
*
* @param string $directory
* @return bool
*/
public function mkdir($directory = null) {
// attempt to create dir
if(ftp_mkdir($this->_stream, $directory)) {
// success
return true;
// fail
} else {
$this->error = "Failed to create directory \"{$directory}\"";
return false;
}
}
/**
* Upload file to server
*
* @param string $local_path
* @param string $remote_file_path
* @param int $mode
* @return bool
*/
public function put($local_file = null, $remote_file = null, $mode = FTP_ASCII) {
// attempt to upload file
if(ftp_put($this->_stream, $remote_file, $local_file, $mode)) {
// success
return true;
// upload failed
} else {
$this->error = "Failed to upload file \"{$local_file}\"";
return false;
}
}
/**
* Get current directory
*
* @return string
*/
public function pwd() {
return ftp_pwd($this->_stream);
}
/**
* Rename file on FTP server
*
* @param string $old_name
* @param string $new_name
* @return bool
*/
public function rename($old_name = null, $new_name = null) {
// attempt rename
if(ftp_rename($this->_stream, $old_name, $new_name)) {
// success
return true;
// fail
} else {
$this->error = "Failed to rename file \"{$old_name}\"";
return false;
}
}
/**
* Remove directory on FTP server
*
* @param string $directory
* @return bool
*/
public function rmdir($directory = null) {
// attempt remove dir
if(ftp_rmdir($this->_stream, $directory)) {
// success
return true;
// fail
} else {
$this->error = "Failed to remove directory \"{$directory}\"";
return false;
}
}
public function getStream()
{
return $this->_stream;
}
public function isDir($dir)
{
return in_array($dir, ftp_nlist($this->_stream, dirname($dir)));
}
public function isFile($file)
{
$res = ftp_size($this->_stream, $file);
return $res != -1 ? TRUE : FALSE;
}
}
<?php
/* Finally, A light, permissions-checking logging class.
*
* Author : Kenneth Katzgrau < katzgrau@gmail.com >
* Date : July 26, 2008
* Comments : Originally written for use with wpSearch
* Website : http://codefury.net
* Version : 1.0
*
* Usage:
* $log = new KLogger ( "log.txt" , KLogger::INFO );
* $log->LogInfo("Returned a million search results"); //Prints to the log file
* $log->LogFATAL("Oh dear."); //Prints to the log file
* $log->LogDebug("x = 5"); //Prints nothing due to priority setting
*/
class KLogger
{
const DEBUG = 1; // Most Verbose
const INFO = 2; // ...
const WARN = 3; // ...
const ERROR = 4; // ...
const FATAL = 5; // Least Verbose
const OFF = 6; // Nothing at all.
const LOG_OPEN = 1;
const OPEN_FAILED = 2;
const LOG_CLOSED = 3;
/* Public members: Not so much of an example of encapsulation, but that's okay. */
public $Log_Status = KLogger::LOG_CLOSED;
public $DateFormat = "Y-m-d G:i:s";
public $MessageQueue;
private $log_file;
private $priority = KLogger::INFO;
private $file_handle;
public function __construct( $filepath , $priority )
{
if ( $priority == KLogger::OFF ) return;
$this->log_file = $filepath;
$this->MessageQueue = array();
$this->priority = $priority;
if ( file_exists( $this->log_file ) )
{
if ( !is_writable($this->log_file) )
{
$this->Log_Status = KLogger::OPEN_FAILED;
$this->MessageQueue[] = "The file exists, but could not be opened for writing. Check that appropriate permissions have been set.";
return;
}
}
if ( $this->file_handle = fopen( $this->log_file , "a" ) )
{
$this->Log_Status = KLogger::LOG_OPEN;
$this->MessageQueue[] = "The log file was opened successfully.";
}
else
{
$this->Log_Status = KLogger::OPEN_FAILED;
$this->MessageQueue[] = "The file could not be opened. Check permissions.";
}
return;
}
public function __destruct()
{
if ( $this->file_handle )
fclose( $this->file_handle );
}
public function LogInfo($line)
{
$this->Log( $line , KLogger::INFO );
}
public function LogDebug($line)
{
$this->Log( $line , KLogger::DEBUG );
}
public function LogWarn($line)
{
$this->Log( $line , KLogger::WARN );
}
public function LogError($line)
{
$this->Log( $line , KLogger::ERROR );
}
public function LogFatal($line)
{
$this->Log( $line , KLogger::FATAL );
}
public function Log($line, $priority)
{
if ( $this->priority <= $priority )
{
$status = $this->getTimeLine( $priority );
$this->WriteFreeFormLine ( "$status $line \n" );
}
}
public function WriteFreeFormLine( $line )
{
if ( $this->Log_Status == KLogger::LOG_OPEN && $this->priority != KLogger::OFF )
{
if (fwrite( $this->file_handle , $line ) === false) {
$this->MessageQueue[] = "The file could not be written to. Check that appropriate permissions have been set.";
}
}
}
private function getTimeLine( $level )
{
$time = date( $this->DateFormat );
switch( $level )
{
case KLogger::INFO:
return "$time - INFO -->";
case KLogger::WARN:
return "$time - WARN -->";
case KLogger::DEBUG:
return "$time - DEBUG -->";
case KLogger::ERROR:
return "$time - ERROR -->";
case KLogger::FATAL:
return "$time - FATAL -->";
default:
return "$time - LOG -->";
}
}
}
<?php
/**
* Abstraktni trida pro stahovani kurzovnich listku ze stranek bank
*
* @date 25-02-2008
* @version 1.0
*
*/
abstract class ExchangeRatesFetcher
{
/**
* URL, odkud se kurzy stahuji
*
* @var string
*/
protected $url;
/**
* kod banky
*
* @var string
*/
protected $bank_code;
/**
* seznam kodu men, ktere chceme stahovat
*
* @var array
*/
protected $important_currencies = array('CAD', 'DKK', 'EUR', 'GBP', 'HUF', 'CHF', 'JPY', 'NOK', 'PLN', 'SEK', 'SKK', 'USD', 'RON', 'RUB', 'AUD');
/**
* pole stazenych hodnot kurzu
*
* @var array
*/
protected $exchange_rates = array();
/**
* konstruktor - nastaveni vychozich hodnot
*
* @param string URL, odkud se kurzy stahuji
*/
public function __construct($url)
{
$this->url = $url;
}
/**
* funkce vraci pole stazenych kurzu (vhodne napr. pro testovaci vypisy)
*
* @return array/false pokud nejsou stazene kurzy vraci false, jinak vraci pole stazenych kurzu
*/
public function getExchangeRates()
{
if (is_array($this->exchange_rates)) {
return $this->exchange_rates;
}
else {
return false;
}
}
/**
* funkce vraci kod banky
*
* @return string
*/
public function getBankCode()
{
return $this->bank_code;
}
/**
* Funkce pro stahnuti kurzovniho listku
*
* Funkce stahne kurzovni listek a ulozi ho do interni promenne $exchange_rates
*/
abstract public function fetch();
}