xml文档格式如下:
- <?xml version="1.0" encoding="utf-8"?>
- <list>
- <company>武汉xxx公司</company>
- <user>
- <name>张三</name>
- <age sex="未知">a</age>
- <height>1</height>
- </user>
- <user>
- <name>李四</name>
- <age sex="女">b</age>
- <height>2</height>
- </user>
- <user>
- <name>王五</name>
- <age sex="男">c</age>
- <height>3</height>
- </user>
- <town parent="0" id="1">台北</town>
- <town parent="1" id="2">板桥</town>
- <town parent="0" id="3">桃园</town>
- </list>
php解析代码:
- header("content-type:text/html; charset=utf-8");
- $xml = simplexml_load_file('a.xml');
- echo $xml->company."<br>";
- echo $xml->town."<br>id:";
- echo $xml->town['id']."<br>parent:";
- echo $xml->town['parent']."<br>";
-
- echo "<br>循环读取:<br>";
- foreach($xml->user as $users){
- echo "-------------------<br>";
- echo "姓名:".$users->name."<br>";
- echo "编号:".$users->age."<br>";
- echo "性别:".$users->age['sex']."<br>";
- echo "序号:".$users->height."<br>";
- }
-
- echo "<br>循环读取:<br>";
- foreach($xml->town as $towns){
- echo "-------------------<br>";
- echo "id:".$towns['id']."<br>";
- echo "归属:".$towns['parent']."<br>";
- echo "地区:".$towns."<br>";
- }
定义和用法:
simplexml_load_file() 函数把 xml 文档载入对象中,如果失败,则返回 false.
语法:simplexml_load_file(file,class,options,ns,is_prefix)
参数 描述
file 必需,规定要使用的 xml 文档.
class 可选,规定新对象的 class.
options 可选,规定附加的 libxml 参数.
ns 可选.
is_prefix 可选.
返回值:返回类 simplexmlelement 的一个对象,该对象的属性包含 xml 文档中的数据,如果失败,则返回 false. |