Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phpMick's avatar
Level 15

Create an XML file.

Hey, What is the easiest way to write an XML file? It's a pretty simple format.

Mick

0 likes
5 replies
phpMick's avatar
Level 15

I need to write these;

<?xml version="1.0" encoding="UTF-8"?>
<label>
    <part_no>123456789</part_no>
    <pattern_description>WHITE</pattern_description>
    <PNBC>123456789</PNBC>
    <BatchNo>20160929-108215</BatchNo>
    <firstLineDescription>dsadsad</firstLineDescription>
    <secondLineDescription>dsadsad</secondLineDescription>
    <fr_description>fdsfdsafds</fr_description>
    <es_description>fdsafdsa</es_description>

    <barcode_no>123456</barcode_no>

    <selector>Chris Smith</selector>
    <packer>Joe Bloggs</packer>
    <image>base64 encoded image
    </image>
    <numberOfLabels>1</numberOfLabels>
    <printerName>IT</printerName>
    <labelSize>large</labelSize>
</label>
ohffs's avatar

...And I thought today couldn't get any longer. Ok, if you literally just need to write xml strings then do :

fwrite(STDOUT, '<some><xml></xml></some>');

If you mean something like 'I want to convert an eloquent model to XML and send it to the user as a response' then maybe you should give some more helpful details...

Snapey's avatar

If the format is fixed then you can either just process as a big string, or you can use a blade template. Put the template tags in as you would html and then use the blade syntax to insert the data. You can also use @if statements if required.

Then run view's render method to convert template+data into string that you can output or dump to file.

Braunson's avatar

If your looking to write to XML from an array... check this out. From there you just need to write to a file which is like so:

$bytes_written = File::put($file, $contents);
if ($bytes_written === false)
{
    die("Error writing to file");
}

Please or to participate in this conversation.