laravel 刀片视图不呈现 xml

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41584185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:06:13  来源:igfitidea点击:

Blade View not rendering xml

laravellaravel-5.3laravel-blade

提问by Gaurav Mehta

I am trying to create an XML file in Laravel. I am passing data to a view.

我正在尝试在 Laravel 中创建一个 XML 文件。我正在将数据传递给视图。

However, the XML is not rendering.

但是,XML 不会呈现。

This is what I am doing in my view

在我看来,这就是我正在做的事情

<?php header('Content-Type: text/xml'); ?>
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

@foreach ($merchants as $merchant)
<url>
<loc>{{ $merchant->merchant_url_text }}</loc>
</url>
@endforeach

</urlset>

This however is just printing the variable $merchant->merchant_url_text multiple times without any structure.

然而,这只是在没有任何结构的情况下多次打印变量 $merchant->merchant_url_text 。

Any help with what I am doing wrong.

对我做错了什么的任何帮助。

回答by John Bupit

You're not sending the headers correctly, which is why your response is being interpreted as text/html. In Laravel, you may use the header method to add a series of headers to the response before sending it back to the user. Here's how:

您没有正确发送标头,这就是为什么您的响应被解释为 text/html 的原因。在 Laravel 中,您可以使用 header 方法在将响应发送回用户之前向响应添加一系列标头。方法如下

return response($content)
        ->withHeaders([
            'Content-Type' => 'text/xml'
        ]);

回答by Arun Code

Normally, blade is a templating engine used to render html and other frontend related stuff. I don't thing you need to render xml in your blade file. Instead you can directly return xml response from your controller.

通常,blade 是用于渲染 html 和其他前端相关内容的模板引擎。我不认为您需要在刀片文件中呈现 xml。相反,您可以直接从控制器返回 xml 响应。

Please try this package.

请试试这个包。

https://packagist.org/packages/jailtonsc/laravel-response-xml

https://packagist.org/packages/jailtonsc/laravel-response-xml

Edit:

编辑:

If trying to build a sitemap or something similar using blade, try the following code.

如果尝试使用刀片构建站点地图或类似内容,请尝试以下代码。

<?php header('Content-Type: text/xml'); ?>
  {{ '<?xml version="1.0"?>' }}
  {{ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' }}

@foreach ($merchants as $merchant)
    {{ '<url>' }}
    {{ "<loc> $merchant->merchant_url_text </loc>" }}
    {{ '</url>' }}
@endforeach

{{ '</urlset>' }}