【问题标题】:Yii2 xml file responseYii2 xml文件响应
【发布时间】:2026-02-01 06:30:01
【问题描述】:

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

【问题讨论】:

  • 为什么要返回多部分表单数据作为响应?那应该是输入法吧? text/htmltext/xmlapplication/json
  • 这是我的api操作的技术要求。 text/xml 看起来更自然,当然
  • 答案是否回答了您的问题?
  • 查看我发布的答案你不应该在控制器中使用echo,因为2.0.14 yii 不允许使用它,应该避免

标签: php yii2 response multipartform-data


【解决方案1】:

您可以通过自定义 XmlResponseFormatter 组件属性 contentType 来更改响应的 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;
}

【讨论】:

    【解决方案2】:

    您可以通过这种方式发送带有自定义内容类型的响应:

    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;
    

    【讨论】: