Search code examples
phpxmllaravellaravel-blade

How to display an XML file in a Laravel blade template?


I load an XML file and get the required element from it. Like that:

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

If I output it via {{dd($exampleElement)}} in the blade template, I get this:

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"
  ]
}

If I output in the standard way via {{$exampleElement}}, then nothing is displayed.

What do I need to do so that the output of the element is in this format?:

<categoryId>2411</categoryId>
<param name="Color">Green</param>
...

enter image description here


Solution

  • You could use SimpleXMLElement's asXML method:

    Return a well-formed XML string based on SimpleXML element

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

    So in your case that would be: {{ $exampleElement->asXML() }}

    If only want show the XML in your template and nothing else, and want the browser to handle output as XML, you should bypass the blade template / view and directly output the XML from your controller with the correct header:

    $xml = simplexml_load_file('example.com');
    $exampleElement = $xml->shop->offers->offer;
    $exampleString = $exampleElement->asXML();
    
    return response($exampleString, 200, [
        'Content-Type' => 'application/xml'
    ]);