使用PHP设置PUT请求主体 [英] Setting PUT request body with PHP
问题描述
我正在尝试使用Google Sheets API的电子表格.values.update( https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update )方法将数据插入电子表格.
I'm trying to use the Google Sheets API's spreadsheets.values.update (https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update) method to insert data into a spreadsheet.
我已经获得了一个正确范围的访问令牌,现在我正尝试通过cURL发送一个PUT请求.我正在使用PHP curl包装器( https://github.com/php- curl-class/php-curl-class ),但是普通的PHP也会很棒.
I've already acquired a correctly scoped access token, and now I'm trying to send a PUT request via cURL. I'm using the PHP curl wrapper (https://github.com/php-curl-class/php-curl-class) but plain PHP would also be great.
这是我到目前为止所拥有的:
Here's what I have so far:
$curl = new Curl();
$curl->setHeader("Authorization","Bearer ".json_decode($a4e->user->google_token)->access_token);
$curl->setOpt(CURLOPT_POSTFIELDS, '{"values": [["Elizabeth", "2", "0.5", "60"]]}');
$curl->put('https://sheets.googleapis.com/v4/spreadsheets/11I1xNv8cHzBGE7uuZtB9fQzbgrz4z7lIaEADfta60nc/values/Sheet1!A1', array(
'valueInputOption' => 'USER_ENTERED'
));
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage;
}
else {
echo json_encode($curl->response);
}
cURL请求成功执行,并返回以下内容:
The cURL request executes successfully, and returns the following:
{"spreadsheetId":"11I1xNv8cHzBGE7uuZtB9fQzbgrz4z7lIaEADfta60nc","updatedRange":"Sheet1!A1"}
{"spreadsheetId":"11I1xNv8cHzBGE7uuZtB9fQzbgrz4z7lIaEADfta60nc","updatedRange":"Sheet1!A1"}
但是,它不会更新工作表中的数据.
However, it does not update the data in the sheet.
有人知道我在做什么错吗? 预先非常感谢.
Does anyone know what I am doing wrong? Many thanks in advance.
推荐答案
OK, so I ran the parameters through Postman (https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) and exported the following code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sheets.googleapis.com/v4/spreadsheets/11I1xNv8cHzBGE7uuZtB9fQzbgrz4z7lIaEADfta60nc/values/Sheet1!A1?valueInputOption=USER_ENTERED",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\"range\":\"Sheet1!A1\",\"majorDimension\":\"ROWS\",\"values\":[[\"x\",\"x\",\"x\",\"x\",\"x\"]]}",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer {token}",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
终于可以了!根据RomanPerekhrest的建议,内容类型:application/json是绝对必要的.没有它,请求不会更新任何内容.
And it finally works! The content-type: application/json is absolutely essential, as per RomanPerekhrest's suggestion. The request doesn't update anything without it.
这篇关于使用PHP设置PUT请求主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!