我有 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
来更改响应的 Content-Type
组件属性 contentType
使用自定义值,然后在运行时设置自定义格式化程序,而不是手动使用 echo
因为 2.0.14
Yii 不允许在 Controller 中回显,因此不应遵循。此外,使用此方法也会自动为 content-type
header 设置 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;
}
关于php - Yii2 xml 文件响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57736821/