dpblwmh5218
dpblwmh5218
2013-08-27 06:41

如何将xml数据保存在一个文件中

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douba8819 douba8819 8年前

    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.

    点赞 评论 复制链接分享

为你推荐