Google表格API - 使用PHP插入一行

时间:2015-07-31 14:06:06

标签: php google-sheets

所以我创建了一个Spreadsheet类,它是我在网上找到的一些用PHP访问Google Sheets API的解决方案的组合。有用。

class Spreadsheet {
    private $token;
    private $spreadsheet;
    private $worksheet;
    private $spreadsheetid;
    private $worksheetid;

    private $client_id = '<client id>';
    private $service_account_name = '<service_account>';  // email address
    private $key_file_location = 'key.p12'; //key.p12

    private $client;
    private $service;

    public function __construct() {
        $this->client = new Google_Client();
        $this->client->setApplicationName("Sheets API Testing");
        $this->service = new Google_Service_Drive($this->client);
        $this->authenticate();
    }
    public function authenticate()
    {
        if (isset($_SESSION['service_token'])) {
            $this->client->setAccessToken($_SESSION['service_token']);
        }
        $key  = file_get_contents($this->key_file_location);
        $cred = new Google_Auth_AssertionCredentials(
            $this->service_account_name,
            array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'),            $key
        );
        $this->client->setAssertionCredentials($cred);
        if ($this->client->getAuth()->isAccessTokenExpired()) {
            $this->client->getAuth()->refreshTokenWithAssertion($cred);
        }
        $_SESSION['service_token'] = $this->client->getAccessToken();

        // Get access token for spreadsheets API calls
        $resultArray = json_decode($_SESSION['service_token']);
        $this->token = $resultArray->access_token;
    }

    public function setSpreadsheet($title) {
        $this->spreadsheet = $title;
        return $this;
    }
    public function setSpreadsheetId($id) {
        $this->spreadsheetid = $id;
        return $this;
    }
    public function setWorksheet($title) {
        $this->worksheet = $title;
        return $this;
    }
    public function insert() {
        if (!empty($this->token)) {
            $url = $this->getPostUrl();
        } else {
            echo "Authentication Failed";
        }
    }
    public function add($data) {
        if(!empty($this->token)) {
            $url = $this->getPostUrl();
            if(!empty($url)) {
                $columnIDs = $this->getColumnIDs();
                if($columnIDs) {
                    $fields = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
                    foreach($data as $key => $value) {
                        $key = $this->formatColumnID($key);
                        if(in_array($key, $columnIDs)) {
                            $fields .= "<gsx:$key><![CDATA[$value]]></gsx:$key>";
                        }
                    }
                    $fields .= '</entry>';

                    $headers = [
                        "Authorization" => "Bearer $this->token", 
                        'Content-Type' => 'application/atom+xml'
                    ];
                    $method = 'POST';
                    $req = new Google_Http_Request($url, $method, $headers, $fields);
                    $curl = new Google_IO_Curl($this->client);
                    $results = $curl->executeRequest($req);
                    var_dump($results);
                }
            }
        }
    }
    private function getColumnIDs() {
        $url = "https://spreadsheets.google.com/feeds/cells/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full?max-row=1";
        $headers = array(
            "Authorization" => "Bearer $this->token",
            "GData-Version: 3.0"
        );

        $method = "GET";
        $req = new Google_Http_Request($url, $method, $headers);
        $curl = new Google_IO_Curl($this->client);
        $results = $curl->executeRequest($req);

        if($results[2] == 200) {

            $columnIDs = array();
            $xml = simplexml_load_string($results[0]);
            if($xml->entry) {
                $columnSize = sizeof($xml->entry);
                for($c = 0; $c < $columnSize; ++$c) {
                    $columnIDs[] = $this->formatColumnID($xml->entry[$c]->content);
                }
            }
            return $columnIDs;
        }
        return "";
    }
    private function getPostUrl() {
        if (empty($this->spreadsheetid)){

            #find the id based on the spreadsheet name
            $url = "https://spreadsheets.google.com/feeds/spreadsheets/private/full?title=" . urlencode($this->spreadsheet);
            $method = 'GET';
            $headers = ["Authorization" => "Bearer $this->token"];
            $req = new Google_Http_Request($url, $method, $headers);
            $curl = new Google_IO_Curl($this->client);
            $results = $curl->executeRequest($req);          

            if($results[2] == 200) {
                $spreadsheetXml = simplexml_load_string($results[0]);
                if($spreadsheetXml->entry) {
                    $this->spreadsheetid = basename(trim($spreadsheetXml->entry[0]->id));
                    $url = "https://spreadsheets.google.com/feeds/worksheets/" . $this->spreadsheetid . "/private/full";
                    if(!empty($this->worksheet)) {
                        $url .= "?title=" . $this->worksheet;
                    }
                    $req = new Google_Http_Request($url, $method, $headers);
                    $response = $curl->executeRequest($req);

                    if($response[2] == 200) {
                        $worksheetXml = simplexml_load_string($response[0]);
                        if($worksheetXml->entry) {
                            $this->worksheetid = basename(trim($worksheetXml->entry[0]->id));
                        }
                    }
                }
            }           
        }


        if(!empty($this->spreadsheetid) && !empty($this->worksheetid)) {
            return "https://spreadsheets.google.com/feeds/list/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full";
        }

        return "";
    }
    private function formatColumnID($val) {
        return preg_replace("/[^a-zA-Z0-9.-]/", "", strtolower($val));
    }
}

然后我使用这个测试php文件将行添加到我的电子表格中:

$Spreadsheet = new Spreadsheet();
$Spreadsheet->
    setSpreadsheet("test spreadsheet")->
    setWorksheet("Sheet1")->
    add(array("name" => "Cell 1", "email" => "Cell 2"));

有了这个,我可以删除一行/更新一行并附加一行。但是,我需要的主要原因是插入一行。有没有人想出办法做到这一点?任何语言都很好,虽然id更喜欢php解决方案。

1 个答案:

答案 0 :(得分:1)

您可以使用HTTPS GET或POST请求从PHP调用Apps Script独立脚本。 PHP可以发出GET或POST请求,而Apps Script显然可以使用SpreadsheetApp服务在任何地方插入行。您可能还希望在Apps脚本代码中使用内容服务,以获得代码完成的退货确认。

您可能希望使用POST请求以获得更好的安全性。因此,您可以再次使用Apps脚本作为PHP和电子表格之间的中介。 Apps脚本文件中的doPost()将需要一个事件处理程序,通常分配给字母&#34; e&#34;:

doPost(e) {
  //Get e and retrieve what the code should do

  //Insert the row

};

另外,请看这个答案:

Stackoverflow - Call a custom GAS function from external URL