[英]Yii2 xml file response
我有xml文件,我想通过Content-Type = multipart / form-data的 http-response在api操作中发送它
现在我正在使用Content-Type = text / xml ,我的动作看起来像
\Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = \Yii::$app->response->headers;
$headers->add('Content-Type', 'text/xml');
$xml = file_get_contents($filePath);
return $xml;
但这不是我想要的。 如何将此响应更改为Content-Type = multipart / form-data ?
通过自定义XmlResponseFormatter
组件属性contentType
以使用自定义值,然后在运行时设置自定义格式器,而不是手动使用echo
可以更改响应的Content-Type
,因为2.0.14
Yii不允许在控制器中执行echo
,因此应该不被追随。 同样使用此方法也会自动为content-type
标头设置charset
。
您应该执行以下操作以遵循常规方法
public function actionResponder()
{
$filePath = $_SERVER['DOCUMENT_ROOT'] . '/assets/test.xml';
$xml = new XmlResponseFormatter();
$xml->contentType = 'multipart/form-data';
Yii::$app->response->format='xml';
Yii::$app->response->formatters['xml']=$xml;
$xmlFile = file_get_contents($filePath);
return $xmlFile;
}
您可以通过以下方式发送具有自定义内容类型的响应:
Yii::$app->response->format = Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'multipart/form-data');
Yii::$app->response->content = file_get_contents($filePath);
return Yii::$app->response;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.