Home > php教程 > php手册 > php Simplexml_Load_file解析xml详细实例

php Simplexml_Load_file解析xml详细实例

WBOY
Release: 2016-05-25 16:41:47
Original
1241 people have browsed it

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>
Copy after login

php解析代码:

header("content-type:text/html; charset=utf-8"); //设置编码 
$xml = simplexml_load_file(&#39;a.xml&#39;);  //载入xml文件 $lists和xml文件的根节点是一样的 
echo $xml->company."<br>"; 
echo $xml->town."<br>id:"; 
echo $xml->town[&#39;id&#39;]."<br>parent:"; 
echo $xml->town[&#39;parent&#39;]."<br>"; 
 
echo "<br>循环读取:<br>"; 
foreach($xml->user as $users){     //有多个user,取得的是数组,循环输出 
    echo "-------------------<br>"; 
    echo "姓名:".$users->name."<br>"; 
    echo "编号:".$users->age."<br>"; 
    echo "性别:".$users->age[&#39;sex&#39;]."<br>"; 
    echo "序号:".$users->height."<br>"; 
} 
echo "<br>循环读取:<br>"; 
foreach($xml->town as $towns){     //有多个user,取得的是数组,循环输出 
    echo "-------------------<br>"; 
    echo "id:".$towns[&#39;id&#39;]."<br>"; 
    echo "归属:".$towns[&#39;parent&#39;]."<br>"; 
    echo "地区:".$towns."<br>"; 
}
Copy after login

定义和用法:

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.


本文地址:

转载随意,但请附上文章地址:-)

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template