在 Laravel 中解析 XML

Ped*_*dro 3 php xml laravel

我试图生成一个 xml,但我收到一个错误: FatalErrorException in 6955f07d83b93bb8aa89577b116866e228e0c155.php line 1 syntax error, unexpected 'version' (T_STRING).

我无法弄清楚我在代码中做错了什么。

我的控制器功能是:

public function feed($gallery_id){
        $products = Products::select("id","title","brand","url","path")->where("gallery_id",$gallery_id)->get();

        foreach ($products as $product) {
            $product->path = url($product->path);
        }
        return response()->view('xml.gallery', compact('products'))->header('Content-Type', 'text/xml');

    }
Run Code Online (Sandbox Code Playgroud)

我的刀片(xml.gallery):

    <?xml version="1.0"?>
    <rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
      <channel>
        <title>Test Store</title>
        <link>http://domain.com</link>
        <description>An example item from the feed</description>
       @?foreach($products as $product)
          <item>
          <g:id>1</g:id>
          <g:title>something</g:title>
          <g:description>Solid plastic Dog Bowl in marine blue color</g:description>
          <g:link>http://www.zara.com</g:link>
          <g:image

_link>http://domain.com/images/photos_gallery/14788772681.png</g:image_link>
      <g:price>12 GBP</g:price>
      <g:brand>Nike</g:brand>
       <g:availability>in stock</g:availability>
       <g:condition>new</g:condition>
    </item>
  @?endforeach
  </channel>
</rss>
Run Code Online (Sandbox Code Playgroud)

Ami*_*pta 8

看起来您short_open_tag已启用。它告诉 PHP 是否(<? ?>)应该允许 PHP 的 open 标签的缩写形式。如果您想将 PHP 与 XML 结合使用,您可以禁用此选项以使用<?xml ?>内联。

但其他简单的解决方案是在您的视图文件中编写以下代码:

<?php echo '<?xml version="1.0"?>'; ?>
Run Code Online (Sandbox Code Playgroud)


ayn*_*ber 5

我们绕过它的方法是将 xml 标头存储为变量,然后将其传递:

$xml_version = '<?xml version="1.0"?>';

return response()->view('xml.gallery', compact('products', 'xml_version'))->header('Content-Type', 'text/xml');
Run Code Online (Sandbox Code Playgroud)

然后您可以将其放入刀片中:

{{$xml_version}}
Run Code Online (Sandbox Code Playgroud)