DOMDocument讀寫XML文件


DOMDocument讀寫XML文件:

 1 <?php
 2 /**
 3 * function:DOMDocument寫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 //XML標簽配置
17 $xmlTag = array(
18     'starttime',
19     'endtime',
20     'school'
21 );
22  
23 $dom = new DOMDocument('1.0', 'utf8');
24 $dom->formatOutput = true;
25 $studentcareer = $dom->createElement('studentcareer');
26 $dom->appendChild($studentcareer);
27 foreach($study as $s) {
28     $period = $dom->createElement('period');
29     $studentcareer->appendChild($period);
30     foreach($xmlTag as $x) {
31         $element = $dom->createElement($x);
32         $period->appendChild($element);
33         $text = $dom->createTextNode($s[$x]);
34         $element->appendChild($text);
35     }
36 }
37 $dom->save('./write_dom.xml');

DOMDocument讀XML文件:

 1 <?php
 2 /**
 3 * function:DOMDocument讀XML文件
 4 * author:JetWu
 5 * date:2016.12.03
 6 **/
 7 //XML標簽配置
 8 $xmlTag = array(
 9     'starttime',
10     'endtime',
11     'school'
12 );
13 $dom = new DOMDocument();
14 $dom->load('./write_dom.xml');
15 $periods = $dom->getElementsByTagName('period');
16 $study = array();
17 foreach($periods as $k => $p) {
18     foreach($xmlTag as $x) {
19         $node = $p->getElementsByTagName($x);
20         $study[$k][$x] = $node->item(0)->nodeValue;
21     }
22 }
23 echo '<pre>';
24 print_r($study);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM