在hyperf中如何输出json格式 , xml格式 及 raw 格式
如何实现跳转
以下如何生成cookie
如何下载
以下为控制器 `app/Controller/IndexController.php`
```
'huyongjian',
'qq'=>'308830232@qq.com'
];
return $response->json($data);
}
/**
* 返回xml格式示例
*/
public function xml(ResponseInterface $response):Psr7ResponseInterface
{
$data = [
'name'=>'huyongjian',
'qq'=>'308830232@qq.com'
];
return $response->xml($data);
}
/**
* 返回raw格式示例
*/
public function raw(ResponseInterface $response):Psr7ResponseInterface
{
$data =[
'name'=>'huyongjian',
'qq'=>'308830232@qq.com'
];
$data = json_encode($data);
return $response->raw($data);
}
/**
* redirect示例
*
*/
public function redirect(ResponseInterface $response):Psr7ResponseInterface
{
return $response->redirect('/index/json');
}
/**
*cookie设置示例
*/
public function cookie(ResponseInterface $response):Psr7ResponseInterface
{
$cookie = new Cookie('name','huyongjian');
return $response->withCookie($cookie)->withContent('Hello Hyperf cookie is ok');
}
/**
* 文件下载示例
*/
public function download(ResponseInterface $response):Psr7ResponseInterface
{
return $response->download(BASE_PATH . '/public/download.txt', 'download.txt');
}
}
```
以下为运行结果
```
添加download.txt public/download.txt
download test
浏览器访问测试
json
http://118.195.173.53:9501/index/json
结果
{"name":"huyongjian","qq":"308830232@qq.com"}
xml
http://118.195.173.53:9501/index/xml
结果
raw
http://118.195.173.53:9501/index/raw
结果
{"name":"huyongjian","qq":"308830232@qq.com"}
redirect
http://118.195.173.53:9501/index/redirect
结果
{"name":"huyongjian","qq":"308830232@qq.com"}
cookie
http://118.195.173.53:9501/index/cookie
结果
Hello Hyperf cookie is ok
Application>Cookies 可以看到设置的cookie值
文件下载
http://118.195.173.53:9501/index/download
```
本文转载 `https://www.cnblogs.com/hu308830232/p/15304155.html`