1

I want to execute a PHP script and create a XML file. The PHP script contains a set of 'echo' commands.

$name = strftime('xml_%m_%d_%Y.xml');
header('Content-Disposition: attachment;filename=' . $name);
header('Content-Type: text/xml');

echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
echo '<lager>'.PHP_EOL;
foreach ($product_array as $product) {
    echo "<product>".PHP_EOL;
    echo "<code>", $product->var_code, "</code>".PHP_EOL;
    echo "<group>", $product->var_group, "</group>".PHP_EOL;
    echo "<manu>", $product->var_manufacturer, "</manu>".PHP_EOL;
    echo "<product>".PHP_EOL;
}
echo '</lager>'.PHP_EOL;

I already did but with this script, the Browser starts to download a file. Instead of that, I want the script to create file and keep at the server.

Dekel
  • 60,707
  • 10
  • 101
  • 129
SlavisaPetkovic
  • 357
  • 3
  • 11
  • 2
    indeed a duplicate. Use output buffering as [http://stackoverflow.com/a/5870612/2286722](this answer). – Marten Koetsier Aug 16 '15 at 15:16
  • @MartenKoetsier My output is about 8-9MB and I tried with this but I get **Internal Server Error** message after 5-6 minutes. Is a solution to increase a max_execuction_time? – SlavisaPetkovic Aug 16 '15 at 15:35
  • @Caci: Supposing that this runs an some server, can you check the server's error log? If this gives an error on max execution time, it will also note how much the max is. Normally this is 30s (apache default). In that case, this may solve your problem. – Marten Koetsier Aug 16 '15 at 15:42
  • 1
    Oh, and there is an error in the output code: the last echo in the `foreach` should be an end-tag: `` (you missed the slash!) (and btw. is this about beer? Nice!) – Marten Koetsier Aug 16 '15 at 15:44

1 Answers1

2
  1. If you don't need to send the file to the user (/browser) you don't need the header functions. These headers exists only to tell the browser what is the type of the content that the server provides.
  2. If you want to save the file in the server - you can use any of file_put_contents or fopen + fwrite functions to do so.

Here is your the code you are looking for. I also fixed the </product> (added the slash you missed there, thanks to @Marten Koetsier)

$name = strftime('xml_%m_%d_%Y.xml');
// Open the file for writing
$fp = fopen($name, 'w');
fwrite($fp, '<?xml version="1.0" encoding="UTF-8"?>');
fwrite($fp, '<lager>');
foreach ($product_array as $product) {
    fwrite($fp, "<product>");
    fwrite($fp, "<code>{$product->var_code}</code>");
    fwrite($fp, "<group>{$product->var_group}</group>");
    fwrite($fp, "<manu>{$product->var_manufacturer}</manu>");
    fwrite($fp, "</product>");
}
fwrite($fp, '</lager>');
fclose($fp);

And since you save it as XML you don't really need the PHP_EOL. You can put i back if you really want...

Dekel
  • 60,707
  • 10
  • 101
  • 129