Fork me on GitHub

XMLWriter和XMLReader读写XML文件

XMLWriter写XML文件:

 1 <?php
 2 /**
 3 * function:XMLWriter写XML文件
 4 * author:JetWu
 5 * date:2016.12.03
 6 **/
 7 $mysqli = mysqli_connect('localhost', 'root', '123456', 'wjt');
 8 if(mysqli_connect_errno()) die('database connect fail:' . mysqli_connect_error());
 9  
10 $sql = 'select * from study order by starttime';
11 $res = mysqli_query($mysqli, $sql);
12 $study = array();
13 while($row = mysqli_fetch_array($res)) {
14     $study[] = $row;
15 }
16  
17 //XML标签配置
18 $xmlTag = array(
19     'starttime',
20     'endtime',
21     'school'
22 );
23  
24 $xml = new XMLWriter();
25 $xml->openUri('./write_WR.xml');
26 $xml->setIndentString('  ');//设置缩进格式化使用的符号
27 $xml->setIndent(true);
28 $xml->startDocument('1.0', 'utf8');
29 $xml->startElement('studentcareer');
30 foreach($study as $s) {
31     $xml->startElement('period');
32     foreach($xmlTag as $x) {
33         $xml->startElement($x);
34         $xml->text($s[$x]);
35         $xml->endElement();
36     }
37     $xml->endElement();
38 }
39 $xml->endElement();
40 $xml->endDocument();
41 $xml->flush();

XMLReader读XML文件:

 1 <?php
 2 /**
 3 * function:XMLReader读XML文件
 4 * author:JetWu
 5 * date:2016.12.03
 6 **/
 7 //XML标签配置
 8 $xmlTag = array(
 9     'starttime',
10     'endtime',
11     'school'
12 );
13 $xml = new XMLReader();
14 $xml->open('./write_WR.xml');
15 $study = array();
16 $count = 0;//记录数:方便组装数据
17 $name = '';
18 while($xml->read()) {
19     $n = $xml->name;
20     if($xml->nodeType == XMLReader::ELEMENT) {
21         if($n == 'period') {//开始下一条记录的读取
22             $count ++;
23         } else if(in_array($n, $xmlTag)) {//记录需要获取文本值的标签名
24             $name = $n;
25         }
26     } else if($xml->nodeType == XMLReader::TEXT) {
27         if(in_array($name, $xmlTag)) {
28             $study[$count][$name] = $xml->value;
29         }
30     }
31 }
32 $xml->close();
33 echo '<pre>';
34 print_r($study);

 

posted @ 2019-03-29 15:23  陌帆  阅读(333)  评论(0编辑  收藏  举报
Live2D