向YouTube API PHP发送请求时出现奇怪错误



我目前正在进行后端处理,该处理请求从PHP上的YouTube analytics API返回频道分析信息。出于某种原因,我一直在中收到一条奇怪的错误消息

foreach ($metrics as $metric) {
$api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams);
print('reached');
foreach ($api->rows as $r) {
print($r[0]);
print($r[1]);
}
}
Fatal error: Uncaught TypeError: array_merge(): Argument #2 must be of type array, string given in ... 

所以我假设错误与$query相关,并且输入应该是数组类型,所以我这样做了:

foreach ($metrics as $metric) {
$params = [$id, $start_date, $end_date, $metric, $optparams];
$api = $analytics->reports->query($params);
print('reached');
foreach ($api->rows as $r) {
print($r[0]);
print($r[1]);
}
}
Fatal error: Uncaught GoogleException: (query) unknown parameter: '0'

但正如你所看到的,一个错误仍然存在。对于第二个,我假设PHP中的数组在技术上是顺序映射,这就是为什么它对"0"是一致的,但我仍然很困惑,如果它不能处理它,为什么它会要求一个数组

关于我的代码的更多上下文,我使用Google API的PHP客户端库,这是我通过composer require google/apiclient:^2.0获得的。这是我实例化所有对象的整个代码文件:

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_YouTubeAnalytics($client);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/Analytics_Dashboard/oauth2callbackYouTube.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// here we set some params
$id = '////////';
$end_date = date("Y-m-d"); 
$start_date = date('Y-m-d', strtotime("-30 days"));
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
);
$metrics = array(
'views',
'estimatedMinutesWatched',
'averageViewDuration',
'comments',
'favoritesAdded',
'favoritesRemoved',
'likes',
'dislikes',
'shares',
'subscribersGained',
'subscribersLost'
);
$api_response = $metrics;
// You can only get one metric at a time, so we loop
foreach ($metrics as $metric)
{
$params = [$id, $start_date, $end_date, $metric, $optparams];
$api = $analytics->reports->query($params);
// if (isset($api['rows'])) $api_response[$metric] = $api['rows'][0][0];
print('reached');
foreach ($api->rows as $r) {
print($r[0]);
print($r[1]);
}
}

如果有使用PHP与YouTube Analytics API交互经验的人能提供任何帮助,我将不胜感激!谢谢

我不确定这是否有效,但如果使用关联数组而不是常规数组呢?

$params = [$id, $start_date, $end_date, $metric, $optparams]; //OLD
$params = [ 
'id' => $id, 
'start_date' => $start_date, 
'end_date' => $end_date, 
'metric' => $metric, 
'opt_params' => $optparams
];

如果它有效,您希望使用compact,只是为了获得一个较短的语法:

$params = compact('id', 'start_date', 'end_date', 'metric', 'opt_params');

参数数组必须包含键值。你应该发送这样的参数数组:

$client->setAccessToken($_SESSION['access_token']);
$youtube = new Google_Service_YouTubeAnalytics($client);
$queryParams = array(
'startDate' => '2016-05-01',
'endDate' => '2016-06-30',
'metrics' => 'views',
'ids' => 'channel==MINE'
);

$report = $youtube->reports->query( $queryParams );

有关每个参数需要如何格式化的更多信息,请查看参数文档。

最新更新