php - Yii2 xml 文件响应

标签 php yii2 response multipartform-data

我有 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/

相关文章:

php - 如何使用 preg_match 查找模式匹配并保存到数组

php - 为 Laravel 5.4 创建自己的邮件提供程序

javascript - yii2 kartik 开关输入类型单选按钮在 javascript 中获取值

php - Yii2 中文件属性的自定义错误消息

request - 使用 MQTT 的 RPC 样式请求

node.js - 解析管道响应有时会得到分块数据

php - MySQL 数据无限滚动

php - fatal error : Uncaught Error: Class 'Omnipay\Omnipay' not found

php - 在 yii findOne() 中使用关系表达式

java - RESTful Web 服务 - 资源上下文和响应问题