読者です 読者をやめる 読者になる 読者になる

PHPからGoogle SpreadsheetをCSVで取得する

ちょっとばかし面倒な作業を自動化するため、
PHPからGoogle SpreadsheetをCSVで取得してみた。

<?php
class GSpread
{
    private $token = null;

    private $username = null;

    private $password = null;

    public function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }

    protected function authenticate($service)
    {
        if(isset($this->token[$service])) {
            return;
        }

        $url = 'https://www.google.com/accounts/ClientLogin';
        $post = array(
            'accountType' => 'HOSTED_OR_GOOGLE',
            'Email' => $this->username,
            'Passwd' => $this->password,
            'service' => $service,
            'source' => 'dev'
        );
        
        $curl = curl_init($url);
        
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        if($status == 200) {
            preg_match('/Auth=([a-z0-9_-]+)/i', $response, $matches);
            $this->token[$service] = $matches[1];
        } else {
            throw new Exception('Google ClientLogin authentication failed.');
        }

    }

    public function getCsv($spreadUrl)
    {
        $service = 'wise';
        $this->authenticate($service);
        
        $url = $spreadUrl . '&output=csv';
        $headers = array(
            'Authorization: GoogleLogin auth=' . $this->token[$service],
            'GData-Version: 3.0'
        );
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);        

        if($status == 200) {
            return $response;
        } else {
            throw new Exception('Error: '.$status);
        }
    }
}