Php Laravel - 如何在浏览器中显示 xml 文件

Far*_*our 1 php xml laravel

我在我的目录中生成了 xml 文件。我想使用 php 在浏览器中显示这个文件?

(我想将其显示为站点地图)

这是我的代码:

   public function siteMap()
    {
        $test_array = array (
            'bla' => 'blub',
            'foo' => 'bar',
            'another_array' => array (
                'stack' => 'overflow',
            ),
        );

        $xml_template_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");

        $this->array_to_xml($test_array,$xml_template_info);
        $xml_template_info->asXML(dirname(__FILE__)."/sitemap.xml") ;
        header('Content-type: text/xml');
        dd(readfile(dirname(__FILE__)."/sitemap.xml"));
    }

    public function array_to_xml(array $arr, \SimpleXMLElement $xml)
    {
      foreach ($arr as $k => $v) {
          is_array($v)
              ? $this->array_to_xml($v, $xml->addChild($k))
              : $xml->addChild($k, $v);
      }
      return $xml;
   }
Run Code Online (Sandbox Code Playgroud)

这是sitemap.xml

<?xml version="1.0"?>
<template><bla>blub</bla><foo>bar</foo><another_array><stack>overflow</stack></another_array></template>
Run Code Online (Sandbox Code Playgroud)

这是结果: 在此处输入图片说明

我想在我的浏览器中显示这个 xml 文件,知道正确执行此操作吗?

已编辑:这是带有header('Content-type: text/plain'); 的结果; 在此处输入图片说明

它由一些额外的报告组成。

小智 6

在您的视图中创建 sitemap.blade.php。
在您的 sitemap.blade.php 中插入内容 xml。
创建一个名为sistemap 的函数。

 public function sitemap(){

     return response()->view('sitemap')->header('Content-Type', 'text/xml');

 }
Run Code Online (Sandbox Code Playgroud)


在您的路线中:

 Route::get('sitemap', function () {
     return view('sitemap');
 });
Run Code Online (Sandbox Code Playgroud)


Ali*_*ili 5

假设 xml 的内容在 $xml 变量中,您可以使用以下方法之一:

return response($xml, 200)->header('Content-Type', 'application/xml');
Run Code Online (Sandbox Code Playgroud)

或者

return response($xml, 200, ['Content-Type' => 'application/xml']);
Run Code Online (Sandbox Code Playgroud)