在我的控制器中,我有一个可以从Google PageSpeed API抓取屏幕截图的功能。当我直接在刀片视图中调用它时,出现一个错误,提示未定义变量$ image 。
当我在纯PHP中使用此功能时,一切正常。有什么事吗 此外:如何仅在功能视图中调用刀片视图?
function getGooglePageSpeedScreenshot($site, $img_tag_attributes = "border='1'")
{
#initialize
$use_cache = false;
$apc_is_loaded = extension_loaded('apc');
#set $use_cache
if ($apc_is_loaded) {
apc_fetch("thumbnail:" . $site, $use_cache);
}
$validateSite = filter_var($site, FILTER_VALIDATE_URL);
if (!$use_cache && $validateSite) {
$image
= file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url="
. urlencode(substr($site, 0,
-strlen(substr(strrchr($site, '/'), 1)))) . "&screenshot=true");
$image = json_decode($image, true);
$image = $image['screenshot']['data'];
if ($apc_is_loaded) {
apc_add("thumbnail:" . $site, $image, 2400);
}
}
$image = str_replace(array('_', '-'), array('/', '+'), $image);
return "<img src=\"data:image/jpeg;base64," . $image . "\" $img_tag_attributes" . "style='width='80, height='80'" . "=/>";
}
在刀片服务器中:
@foreach($topStories as $story)
<img src="{{ (new App\Http\Controllers\DashboardController)->getThumbnail($story->Url) }}" style="width: 50px; height: 50px">
<a href="{{$story->Url}}">{{$story->Title}}</a><br>
@endforeach
{{$topStories->links()}}
答案 0 :(得分:0)
请按以下方式更新您的功能:
<?php
function getGooglePageSpeedScreenshot($site, $img_tag_attributes = "border='1'")
{
if (empty(trim($site))) {
return NULL; // for empty $site, return nothing
}
// check cache
$apc_is_loaded = extension_loaded('apc');
if ($apc_is_loaded) {
$has_cache = false;
$cached = apc_fetch("thumbnail:" . $site, $has_cache);
if ($has_cache) return $cached;
}
// check $site for valid URL
if (filter_var($site, FILTER_VALIDATE_URL) === FALSE) {
throw new \Exception(sprintf('invalid URL: %s', $site));
return NULL;
}
// get pagespeed API response for the URL
$response = file_get_contents('https://www.googleapis.com/pagespeedonline/v1/runPagespeed?' . http_build_query([
'url' => (array_key_exists('path', parse_url($site))) ? dirname($site) : $site,
'screenshot' => 'true',
]));
$image = json_decode($response, true);
$image = $image['screenshot']['data'];
if ($apc_is_loaded) apc_add("thumbnail:" . $site, $image, 2400);
$image = str_replace(array('_', '-'), array('/', '+'), $image);
return "<img src=\"data:image/jpeg;base64," . $image . "\" $img_tag_attributes" . "style='width='80, height='80'" . "=/>";
}
$site
验证出错时,您将看到出现问题的URL。然后,您需要弄清楚如何修复$site
源数据。