user2663217
user2663217

Reputation: 1

how to save xml data in one file

I am begginer in the php part so please help me out.This is my php script which help to generate the XML file

<?php

   mysql_connect('localhost', 'root', 'root');
   mysql_select_db('dcu');


   $sql = "SELECT meterId FROM meter";
   $res = mysql_query($sql);
   $xml = new XMLWriter();

$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);

$xml->startElement('meteries');
while ($row = mysql_fetch_assoc($res)) {


   $xml->startElement("meterId");
   $xml->writeRaw($row['meterId']);
   $xml->endElement();

    }

$xml->endElement();


   header('Content-type: text/xml');
   $xml->flush();
   ?>
   After running this php script i got this xml file in my terminal as well as in browser

  <?xml version="1.0"?>
   <cemeteries>
 <meterId>1</meterId>
 <meterId>2</meterId>
</cemeteries>

My question was how to save this generated xml in some other xml file

Thanks

Upvotes: 0

Views: 173

Answers (1)

Charlie Vieillard
Charlie Vieillard

Reputation: 792

If you want to save it on the server you can do like this:

<?php

mysql_connect('localhost', 'root', 'root');
mysql_select_db('dcu');

$sql = "SELECT meterId FROM meter";
$res = mysql_query($sql);
$xml = new XMLWriter();

$xml->openMemory();
$xml->startDocument();
$xml->setIndent(true);

$xml->startElement('meteries');

while ($row = mysql_fetch_assoc($res))
{
    $xml->startElement("meterId");
    $xml->writeRaw($row['meterId']);
    $xml->endElement();
}

$xml->endElement();

$content = $xml->flush();

$fp = fopen('data.xml', 'w');
fwrite($fp, $content);
fclose($fp);

header('Content-type: text/xml');
echo $content;

On fopen() in mode 'w' if the file does not exist PHP will attempt to create it. Be sure PHP has sufficient rights to write.

Upvotes: 1

Related Questions