Tiago Oliveira
Tiago Oliveira

Reputation: 1602

Save formated xml to file in PHP

I know that there are a ton of questions about this here but every answer i tried didn't fixed my problem

Problem

I have xml saved on a string and i want so save it to a file but don't want the xml to be in a single line i want to write to the file in pritty print

Also there is a bigger problem with this the instead of the this " it shows this " since this file will be loaded in a diferent website i can't have "

Note that the $content variable has " not "

I know that \n doesn't matter but to make it easier to analize the generated xml file i need the xml to be formated

this is what i am using

$dirname = "temp/" . uniqid();
mkdir($dirname);

$filename = $dirname . "/gen.xml";

$doc = new DomDocument($content);
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->save($filename);

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=gen.xml");
header("Content-Type: application/octet-stream; "); 
header("Content-Transfer-Encoding: binary");

readfile($filename);

$fh = fopen($filename, 'a');
fclose($fh);
unlink($filename);
rmdir($dirname);

I also tried

header("Content-type: text/xml"); and file_put_contents

Upvotes: 1

Views: 294

Answers (1)

DCrystal
DCrystal

Reputation: 721

DomDocument's constructor does not accept an xml string - rather, an optional version and encoding.

What you probably want is to load your $content xml string instead:

$doc = new DOMDocument();

$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->loadXML($content);

$doc->save($filename);

Upvotes: 2

Related Questions