使用 PHP 和 CURL 编辑 Google 表格





5.00/5 (1投票)
如何使用 PHP 和 CURL 编辑 Google 表格
此文来自外部博客。您可以 在此处查看原文或订阅。
我想编辑一个 Google 表格,特别是更改工作表的标题——尽管相同的概念适用于任何类型的表格编辑。我正在使用 PHP,由于没有为此提供客户端 API,我正在使用 CURL 构建 HTTP 请求。
弄清楚这一点简直是一场噩梦。 文档 至少可以说是稀疏的,尤其是在使用 PHP 发送原始请求时。话虽如此,重要的是您 先阅读全部,不要只相信我的说法。
向下滚动以获取完整版本,包括调试和解释性注释。
如果您通过 Google 搜索来到这里,我不会阻止您进一步复制和粘贴代码
$accessToken = "your access token";
$editUrl = "https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId?v=3.0&
access_token=$accessToken";
$entry = "<?xml version='1.0' encoding='UTF-8'?>
<entry>... snip ... </entry>"; //This is the entry element for the worksheet,
//containing any required changes.
$fh = fopen('php://temp','rw+');
fwrite( $fh, $entry);
rewind($fh);
$handle = curl_init ($editUrl);
if ($handle) {
$curlOptArr = array(
CURLOPT_PUT => TRUE, //It's a PUT request.
CURLOPT_INFILESIZE => strlen($entry), //Size of the uploaded content
CURLOPT_INFILE => $fh, //Uploaded content
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE, //Req'd if the google SSL certificate isn't installed
CURLOPT_HTTPHEADER => Array
("content-type: application/atom+xml")); //Include a content-type header!
curl_setopt_array($handle, $curlOptArr);
$ret = curl_exec($handle);
curl_close($handle);
}
fclose($fh);
好的,那么让我们分解一下,并包含我用来调试整个过程并弄清楚 CURL 实际操作的完整示例。
首先,由于 CURL 接受要上传的文件,而我们只有内存中的 string
,因此我们需要使用 PHP 的“临时”文件访问来模拟文件句柄
$fh = fopen('php://temp','rw+');
fwrite( $fh, $entry);
rewind($fh);
创建另一个文件句柄以接受调试日志
$debugOutput = fopen('php://temp', 'rw+');
然后,使用所有调试技巧设置 CURL 选项
$curlOptArr = array(
CURLOPT_PUT => TRUE,
CURLOPT_INFILESIZE => strlen($entry),
CURLOPT_INFILE => $fh,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_VERBOSE => TRUE, //Ensure lots of debug output
CURLOPT_STDERR => $debugOutput, //Writes loads of stuff to the debug file
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => Array("content-type: application/atom+xml")
);
现在创建 CURL 对象,提交请求并输出所有漂亮的调试信息。
$handle = curl_init ($editUrl);
curl_setopt_array($handle, $curlOptArr);
$ret = curl_exec($handle);
$errRet = curl_error($handle);
print("Result: $ret<br>");
print("Error: $errRet<br>");
print_r(curl_getinfo($handle));
!rewind($debugOutput);
$verboseLog = stream_get_contents($debugOutput);
echo "Verbose information:\n<pre>",
htmlspecialchars($verboseLog), "</pre>";
别忘了关闭句柄。
curl_close($handle);
fclose($debugOutput);
fclose($fh);