You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP脚本输出的SVG无法在img标签显示的问题及解决

SVG无法通过PHP脚本在img标签中显示的问题及解决办法

我尝试通过PHP脚本读取SVG文件并返回数据,原PHP代码如下:

$file = dirname(__FILE__) . $_GET["file"] . ".svg";

if (!file_exists($file)) {
    $file = dirname(__FILE__) . $_GET["file"] . ".png";
    if (!file_exists($file)) {
        throw new NotFoundHttpException();
    } else
        header('Content-Type: image/png');
} else
    header('Content-Type: image/svg+xml');

$content = file_get_contents($file);
return $content;

HTML中的调用方式:

<img src="script.php?file=someimage">

问题现象

  • SVG无法在img标签中显示,但直接在浏览器地址栏访问该脚本URL可以正常显示
  • PNG图片通过该脚本能正常在img标签中显示
  • 直接使用<img src="someimage.svg">可正常显示SVG
  • embed和object标签能显示SVG,但需求是必须使用img标签

问题原因及解决办法

问题根源在于Yii2框架中响应头的设置方式错误:原代码用header()函数设置Content-Type的方式对PNG有效,但对SVG无效。正确的设置方式需使用Yii2内置的响应处理机制:

Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'image/svg+xml');

内容的提问来源于stack exchange,提问作者Pau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:15:36