使用PHP生成和获取XML格式数据
1.php生成xml
代码如下:
<?php header("content-type:text/html;charset=utf-8"); $con = mysql_connect('localhost','root','root'); mysql_query('set names utf8'); $db = mysql_select_db('wh'); // var_dump($con,$db); $sql = "select * from stu"; $res = mysql_query($sql)or die(mysql_error()); while($row=mysql_fetch_assoc($res)){ $arr[] = array( 'name' => $row['name'], 'age' => $row['age'], 'email' => $row['email'] ); } $doc = new DOMDocument('1.0', 'utf-8'); // 声明版本和编码 // var_dump($doc); $doc->formatOutput = true; $r = $doc->createElement("root"); $doc->appendChild($r); foreach ($arr as $dat) { $b = $doc->createElement("data"); $name = $doc->createElement("name"); $name->appendChild($doc->createTextNode($dat['name'])); $b->appendChild($name); $sex = $doc->createElement("age"); $sex->appendChild($doc->createTextNode($dat['age'])); $b->appendChild($sex); $age = $doc->createElement("email"); $age->appendChild($doc->createTextNode($dat['email'])); $b->appendChild($age); $r->appendChild($b); } echo $doc->saveXML(); ?>
2.读取xml文件信息
a.准备xml文件: f.xml。如:
<?xml version="1.0" encoding="utf-8"?> <root> <data> <name>wuheng</name> <age>23</age> <email>demo@qq.com</email> </data> <data> <name>wuheng009</name> <age>22</age> <email>dem6@qq.com</email> </data> <data> <name>wuheng555</name> <age>22</age> <email>dem6@qq.com</email> </data> <data> <name>xia</name> <age>11</age> <email>456@qq.com</email> </data> <data> <name>xia11</name> <age>12</age> <email>466@qq.com</email> </data> </root>
b.具体的代码,如下:
<?php header("content-type:text/html;charset=utf-8"); $url = "f.xml"; $reader = new XMLReader(); //实例化XMLReader $reader->open($url); //获取xml $i=1; while ($reader->read()) { if ($reader->nodeType == XMLReader::TEXT) { //判断node类型 $m = $i%3; if($m==1) $name = $reader->value; //读取node值 if($m==2) $age = $reader->value; if($m==0){ $email = $reader->value; $arr[] = array( 'name' => $name, 'age' => $age, 'email' => $email ); } $i++; } } print_r($arr); ?>
起点在哪,或许选择不了。重要的是,你追求的终点在哪!