Laravel:控制器函数中未定义的变量

Laravel: Undefined variable in controller funtion

在我的控制器中,我有一个从 Google PageSpeed API 抓取屏幕截图的功能。当我在 blade 视图中直接调用它时出现一个错误,即 变量 $image 未定义.

当我在 php 中使用此功能时,一切正常。有什么问题吗? 加:如何调用blade查看函数的结果呢?

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'" . "=/>";

}

在blade中:

@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()}}

请像这样更新您的函数:

<?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 源数据。