如何在 Laravel 刀片模板中显示 XML 文件?

问题描述 投票:0回答:1

我加载一个 XML 文件并从中获取所需的元素。 像这样:

$xml = simplexml_load_file('example.com');
$$exampleElement = $xml->shop->offers->offer;

如果我通过刀片模板中的 {{dd($exampleElement)}} 输出它,我会得到:

SimpleXMLElement {#478 ▼
  +"@attributes": array:3 [▶
    "id" => "835376"
    "available" => "false"
  ]
  +"categoryId": "2411"
   ...
  +"oldprice": "2690"
  +"param": array:7 [▶
    0 => SimpleXMLElement {#1642 ▶
      +"@attributes": array:1 [▶
        "name" => "Color"
      ]
      +"0": "Green"
    }
    1 => SimpleXMLElement {#1643 ▶
      +"@attributes": array:1 [▶
        "name" => "Brand"
      ]
      +"0": "Adidas"
    }
    ...
  ]
  +"picture": array:2 [▶
    0 => "https://example.com/1.jpg"
    1 => "https://example.com/2.jpg"
  ]
}

如果我通过 {{$exampleElement}} 以标准方式输出,则不会显示任何内容。

我需要做什么才能使元素的输出采用这种格式?:

<categoryId>2411</categoryId>
<param name="Color">Green</param>
...
php xml laravel laravel-blade
1个回答
0
投票

您可以使用 SimpleXMLElement 的

asXML
方法:

返回基于 SimpleXML 元素的格式良好的 XML 字符串

https://www.php.net/manual/en/simplexmlelement.asxml.php

所以在你的情况下是:

{{ $exampleElement->asXML() }}

如果只想在模板中显示 XML 而没有其他内容,并且希望浏览器将输出处理为 XML,则应绕过刀片模板/视图并直接从控制器输出带有正确标头的 XML:

$xml = simplexml_load_file('example.com');
$exampleElement = $xml->shop->offers->offer;
$exampleString = $exampleElement->asXML();

return response($exampleString, 200, [
    'Content-Type' => 'application/xml'
]);

© www.soinside.com 2019 - 2024. All rights reserved.