【发布时间】:2021-06-06 06:20:31
【问题描述】:
在下面的这段代码中,我刚刚在浏览器中生成了一个 .xml 页面,该页面显示了分销商路线的特定站点地图。
我只想将这个生成的 .xml 保存在一个文件中(在 /public/sitemap 文件夹中)。
我拥有的,以及我想使用的,只有这两个(就像控制器底部的渲染):
- urls 数组(参见:foreach 内部)
- xml文件的模板
我已经找到了一个可能的解决方案,但是不实用,而且不是我想要的。 (Create new xml file and save in system using symfony2.8)
控制器:
/**
* @Route("/sitemap/sitemap.xml", name="distributor_sitemap", defaults={"_format"="xml"})
*/
public function getSitemap(Request $request) : Response
{
$urls = [];
$hostname = $request->getSchemeAndHttpHost();
// return an array of routes
$routes = $this->sitemapService->getThreeRoutesByIndexes('/distributor/');
foreach ($routes as $route){
$urls[] = array('loc' => $this->generateUrl($route));
}
// save locally the file
// -----------------------------
// ----- add the code HERE -----
// -----------------------------
// return response in XML format
$response = new Response(
$this->renderView('sitemap/sitemap.html.twig', array(
'urls' => $urls,
'hostname' => $hostname
))
);
$response->headers->set('Content-type', 'text/xml');
return $response;
}
模板:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
{% for url in urls %}
<url>{# check if hostname is not alreay in url#}
<loc>{%if url.loc|replace({hostname:''}) == url.loc%}{{hostname}}{{url.loc}}{%else%}{{url.loc}}{%endif%}</loc>
{% if url.lastmod is defined %}
<lastmod>{{url.lastmod}}</lastmod>
{% endif %}
{% if url.changefreq is defined %}
<changefreq>{{url.changefreq}}</changefreq>
{% endif %}
{% if url.priority is defined %}
<priority>{{url.priority}}</priority>
{% endif %}
{% if url.image is defined and url.image is not empty %}
<image:image>
<image:loc>{%if url.image.loc|replace({hostname:''}) == url.image.loc%}{{hostname}}{{url.image.loc}}{%else%}{{url.image.loc}}{%endif%}</image:loc>
<image:title>{{ url.image.title }}</image:title>
</image:image>
{% endif %}
</url>
{% endfor %}
所以最终的结果还是在 /public/sitemap 文件夹中生成一个 .xml 文件,并且该文件必须包含模板处理的 urls 数组信息,如浏览器中所示。 (所有代码都应该添加到---- add the code HERE ----附近的Controller中)
【问题讨论】:
-
你到底做了什么来完成这项工作?为什么不读取 Twig 的输出并将其写入文件?
标签: symfony