dpblwmh5218 2013-08-27 06:41
浏览 51

如何将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 2013-08-27 07:27
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog