我在循环内的每个页面项目(当前只有 15 个项目)上调用对 youtube 或 Vimeo API 的请求。这工作正常,但页面加载相当滞后。有什么方法可以加快这个过程吗?任何例子都会很棒。
foreach ($videos as $video) {
if ($video->getAttribute('video_id_youtube')) {
$video_id = $video->getAttribute('video_id_youtube');
$youtube = $json->decode($fh->getContents('https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&key=AIzaSyDED8cj2zy37JETK15jwaS5JBkTyJSd9yZ%20&part=snippet,contentDetails,statistics,status'));
$time = strtotime($youtube->items[0]->snippet->publishedAt);
$time_elapsed = $phph->ago($time);
$published_time = $time_elapsed .' ago';
$views = number_format($youtube->items[0]->statistics->viewCount) . ' views';
$poster = $youtube->items[0]->snippet->thumbnails->high->url;
} elseif ($video->getAttribute('video_id_vimeo')) {
$video_id = $video->getAttribute('video_id_vimeo');
$vim = $json->decode($fh->getContents('http://vimeo.com/api/v2/video/'.$video_id.'.json'));
$vim_time = strtotime($vim[0]->upload_date);
$vim_time_elapsed = $phph->ago($vim_time);
$published_time = $vim_time_elapsed .' ago';
$views = number_format($vim[0]->stats_number_of_plays) . ' views';
$poster = $vim[0]->thumbnail_medium;
}
}
您可以每 n 分钟在 cron 中运行对 API 的查询,将其缓存(例如,在 MySQL 数据库中)并仅在您的网站上显示缓存的信息(应该快速加载)。
我觉得,当你/我调用 api 时,它总是变得非常慢。没有尝试过 vimeo,但是 facebook 和 youtube 变得非常慢。当我找到解决方法时。我会让你知道的
这不是测试,而是基于“kije”的想法,只是没有 cron 作业。 该脚本会将请求的 JSON 缓存一天,这意味着它的加载速度比每次发出请求都要快。
在变量
$cacheTime
中,您可以轻松定义JSON将被缓存多长时间。
// how many seconds the file should be cached
$cacheTime = 86400;
// path to your cache directory
$cacheDir = "/path/to/your/cachefolder/";
foreach ($videos as $video) {
if ($video->getAttribute('video_id_youtube')) {
$video_id = $video->getAttribute('video_id_youtube');
$filename = $cacheDir.$video_id.".json";
// NOT tested: ( filemtime( $filename ) > ( time() - $cacheTime ) )
// but you should get the idea?
if( file_exists( $filename ) && ( filemtime( $filename ) > ( time() - $cacheTime ) ) ) {
$youtube = $json->decode( file_get_contents( $filename ) );
} else {
$youtubeJSON = $fh->getContents('https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&key=AIzaSyDED8cj2zy37JETK15jwaS5JBkTyJSd9yZ%20&part=snippet,contentDetails,statistics,status');
$youtube = $json->decode( $youtubeJSON );
// cache the file
file_put_contents( $filename, $youtubeJSON );
}
$time = strtotime($youtube->items[0]->snippet->publishedAt);
$time_elapsed = $phph->ago($time);
$published_time = $time_elapsed .' ago';
$views = number_format($youtube->items[0]->statistics->viewCount) . ' views';
$poster = $youtube->items[0]->snippet->thumbnails->high->url;
}