PHP5 推出了一套新的XML 处理函数,即SimpleXML。名如其实,SimpleXML 本身小 巧精干,只提供了少量的几个方法函数,但用它处理起XML 文件功能却非常强大,操作也 非常的简单。
SimpleXML生成XML文件
<?php //生成一个xml文件 //xml字符串 $_xml = <<<_xml <?xml version="1.0" encoding="utf-8"?> <root> <version>1.0</version> <info>xml解析测试</info> <user> <name>admin博客网</name> <url>http://www.baiduyo.com</url> <author sex="男">admin</author> </user> <user> <name>百度</name> <url>http://www.baidu.com</url> <author sex="女">李彦宏</author> </user> <user> <name>淘宝网</name> <url>http://www.baotao.com</url> <author sex="男">马云</author> </user> </root> _xml; //创建一个simplexml对象,传入xml字符串 $_sxe = new SimpleXMLElement($_xml); //生成xml文件 $_sxe->asXML('test.xml'); ?>
SimpleXML读取XML文件
<?php //载入xml文件,simplexml $_sxe = simplexml_load_file('test.xml'); //测试 echo $_sxe->asXML(); //print_r($_sxe); //var_dump($_sxe); //Reflection::export(new ReflectionClass($_sxe)); ?>
读取节点方法1:
<?php //载入xml $_sxe = simplexml_load_file('test.xml'); //读一级标签的值 //echo $_sxe->version; //如果有多个version标签$_sxe->version其实是一个数组 //print_r($_sxe->version); //echo $_sxe->version[2]; //遍历version标签 // foreach ($_sxe->version as $_v) { // echo '['.$_v.']'; // } //如果要访问二级标签,必须一层一层指明 //echo $_sxe->user[1]->name; //遍历所有的name值 // foreach ($_sxe->user as $_user) { // echo '['.$_user->name.']'; // } //输出第二个user里的author的性别 echo $_sxe->user[1]->author->attributes(); ?>
读取节点方法2:使用xpath来获取xml节点:
<?php //使用xpath来获取xml节点操作 //载入xml $_sxe = simplexml_load_file('test.xml'); //获取version的值 $_version = $_sxe->xpath('/root/version'); //print_r($_version); //echo $_version[1]; // foreach ($_version as $_v) { // echo $_v; // } //访问二级节点 $_name = $_sxe->xpath('/root/user/name'); //print_r($_name); // echo $_name[0]; $_author = $_sxe->xpath('/root/user/author'); echo $_author[1]->attributes(); ?>