thinkphp6设置Content-type解决header添加不生效问题
原生php只需要加入header就可以实现输出各种格式的文件内容,如
header("Content-type: text/css");
然而,在thinkphp6中却不能生效。response总会自动的将内容以网页的形式输出。即自动添加<html>
、<body>
等标签,无法达到预期的效果。
tp6框架中提供了一些如Json、Xml等格式的支持类,但不能解决小编需要的Css格式问题。小编需要的效果是这样的:
body {color: red}
然而实际效果却是这样的:
body {color: red}
小编在网上求索了很久,解决问题过程之艰辛充分体现了业余两个字。
最终解决方案如下:
/vendor/topthink/framework/src/think/response 目录新建 Css.php文件,代码如下:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace think\response;
use think\Cookie;
use think\Response;
/**
* Css Response
*/
class Css extends Response
{
/**
* 输出type
* @var string
*/
protected $contentType = 'text/css';
public function __construct(Cookie $cookie, $data = '', int $code = 200)
{
$this->init($data, $code);
$this->cookie = $cookie;
}
}
在需要返回自定义Content-type的地方,关键代码如下:
use think\Response\Css;
use think\exception\HttpResponseException;
$type = array("Content-type", "text/css");
$response = Css::create($css, 'Css')->header($type);
throw new HttpResponseException($response);
至此,问题解决。
最后,感谢网友slmhvip提供的关键解决信息