php Simplexml_Load_file解析xml详细实例

 更新时间:2016年11月25日 16:54  点击:1877

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');  //载入xml文件 $lists和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){     //有多个user,取得的是数组,循环输出
    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){     //有多个user,取得的是数组,循环输出
    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

分别是创建、增加、删除、修改四个功能,变量都是写死的,改一改用$_post方式接收就可以用了
//index.php教程 创建功能
复制代码 代码如下:
<?php
$xmlpatch = 'index.xml';
$_id = '1';
$_title = 'title1';
$_content = 'content1';
$_author = 'author1';
$_sendtime = 'time1';
$_htmlpatch = '1.html';
111cn.net$doc = new domdocument('1.0', 'utf-8');
$doc -> formatoutput = true;
111cn.net$root = $doc -> createelement('root');//新建节点
111cn.net$index = $doc -> createelement('index');//新建节点
111cn.net$url = $doc -> createattribute('url');//新建属性
$patch = $doc -> createtextnode($_htmlpatch);//新建text值
$url -> appendchild($patch);//将$patch文本设为$url属性的值
111cn.net$id = $doc -> createattribute('id');
$newsid = $doc -> createtextnode($_id);
$id -> appendchild($newsid);
111cn.net$title = $doc -> createattribute('title');
$newstitle = $doc -> createtextnode($_title);
$title -> appendchild($newstitle);
111cn.net$content = $doc -> createtextnode($_content);//节点值
111cn.net$author = $doc -> createattribute('author');
$newsauthor = $doc -> createtextnode($_author);
$author -> appendchild($newsauthor);
111cn.net$sendtime = $doc -> createattribute('time');
$newssendtime = $doc -> createtextnode($_sendtime);
$sendtime -> appendchild($newssendtime);
111cn.net$index -> appendchild($id);//将$id设为index节点的属性,以下类同
$index -> appendchild($title);
$index -> appendchild($content);
$index -> appendchild($url);
$index -> appendchild($author);
$index -> appendchild($sendtime);
111cn.net$root -> appendchild($index);//设置index为root字节点
111cn.net$doc -> appendchild($root);//设置root为跟节点
111cn.net$doc -> save($xmlpatch);//保存文件
111cn.netecho $xmlpatch . ' has create success';
111cn.net?>
111cn.net<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>xml操作</title>
</head>
111cn.net<body>
</body>
</html>

//add.php 增加功能(跟index.php文件差不多,主要就是加个load载入跟 $root = $doc -> documentelement获得跟节点
复制代码 代码如下:
<?php
$xmlpatch = 'index.xml';
$_id = '2';
$_title = 'title2';
$_content = 'content2';
$_author = 'author2';
$_sendtime = 'time2';
$_htmlpatch = '2.html';
111cn.net$doc = new domdocument();
$doc -> formatoutput = true;
if($doc -> load($xmlpatch)) {
$root = $doc -> documentelement;//获得根节点(root)
$index = $doc -> createelement('index');
111cn.net$url = $doc -> createattribute('url');
$patch = $doc -> createtextnode($_htmlpatch);
$url -> appendchild($patch);
111cn.net$id = $doc -> createattribute('id');
$newsid = $doc -> createtextnode($_id);
$id -> appendchild($newsid);
111cn.net$title = $doc -> createattribute('title');
$newstitle = $doc -> createtextnode($_title);
$title -> appendchild($newstitle);
111cn.net$content = $doc -> createtextnode($_content);
111cn.net$author = $doc -> createattribute('author');
$newsauthor = $doc -> createtextnode($_author);
$author -> appendchild($newsauthor);
111cn.net$sendtime = $doc -> createattribute('time');
$newssendtime = $doc -> createtextnode($_sendtime);
$sendtime -> appendchild($newssendtime);
111cn.net$index -> appendchild($id);
$index -> appendchild($title);
$index -> appendchild($content);
$index -> appendchild($url);
$index -> appendchild($author);
$index -> appendchild($sendtime);
111cn.net$root -> appendchild($index);
111cn.net$doc -> save($xmlpatch);
111cn.netecho $_id . ' has been added in ' . $xmlpatch;
111cn.net} else {
echo 'xml file loaded error!';
}
?>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>xml操作-添加</title>
</head>
111cn.net<body>
</body>
</html>

//edit.php 修改功能(这里只修改title属性值 跟节点值)
复制代码 代码如下:
<?php
$xmlpatch = 'index.xml';
$_id = '2';
$_title = 'has been changed';
$_content = 'has been changed';
111cn.net$doc = new domdocument();
$doc -> formatoutput = true;
111cn.netif($doc -> load($xmlpatch)) {
$root = $doc -> documentelement;
$elm = $root -> getelementsbytagname('index');
$checkexist = 0;
foreach ($elm as $new) {
if($new -> getattribute('id') == $_id) {
$new -> setattribute('title', $_title);
$new -> nodevalue = $_content;//修改节点值,真是太意外了,没想到跟js一样直接能赋值...
//$new -> removechild($new -> nodevalue);
$checkexist = 1;
}
}
if($checkexist == 0) {
echo $_id . ' is not found in ' . $xmlpatch;
} else {
$doc -> save($xmlpatch);
echo $_id . ' has been changed';
}
} else {
echo 'xml file loaded error!';
}
111cn.net?>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>xml操作-修改</title>
</head>
111cn.net<body>
</body>
</html>

//del.php 删除功能
复制代码 代码如下:
<?php
$xmlpatch = 'index.xml';
$_id = '2';
111cn.net$doc = new domdocument();
$doc -> formatoutput = true;
if($doc -> load($xmlpatch)) {
$root = $doc -> documentelement;
$elm = $root -> getelementsbytagname('index');
foreach ($elm as $new) {
if($new -> getattribute('id') == $_id) {
if($root -> removechild($new)) {
echo $_id . ' has been deleted';
} else {
echo $_id . ' delete failed';
}
}
}
$doc -> save($xmlpatch);
} else {
echo 'xml file loaded error!';
}
111cn.net?>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>xml操作-删除</title>
</head>
111cn.net<body>
</body>
</html>

 

本文章提供二种生成xml的方法,第一种是直接查询数据库查询在php 页面输出xml格式的数据,第二种方法是利用了php DOMDocument组件生成xml实例原理有一点不同。
 代码如下 复制代码

$sql = "查询数据库文件";
$query = mysql教程_query($sql);
echo "<?xml version='1.0' encoding='utf-8' ?>";
echo "<photos>";
while(@$result = mysql_fetch_array($query)){

echo "<photo desc='$result[文件名字段]' url='_pics/$result[文件名字段]' />";

}
echo "</photos>";
//--------------------------------------------------------
$this->_delimage('/_pics');

function _delimage($path){
 if(is_dir($path)){
   $dp=dir($path);
   while($file=$dp->read())
    if($file!='.'&&$file!='..'){
     $this->_delimage($path.'/'.$file);
    }
    $dp->close();
  }
echo "<photo desc='$path' url='$path' />";
}

//利用domdocument

 
   
$doc=new domdocument("1.0","gb2312");  #声明文档类型  
$doc->formatoutput=true;               #设置可以输出操作  
 
#声明根节点,最好一个xml文件有个跟节点  
$root=$doc->createelement("root");    #创建节点对象实体   
$root=$doc->appendchild($root);      #把节点添加进来  
    
   # for($i=1;$i<100;$i++){  //循环生成节点,如果数据库调用出来就改这里  
    
   $info=$doc->createelement("info");  #创建节点对象实体  
   $info=$root->appendchild($info);    #把节点添加到root节点的子节点  
 
        $namevalue=$doc->createattribute("value");  #创建节点属性对象实体   
        $namevalue=$info->appendchild($namevalue);  #把属性添加到节点info中  
         
        $name=$doc->createelement("name");    #创建节点对象实体         
        $name=$info->appendchild($name);  
         
        $sex=$doc->createelement("sex");  
        $sex=$info->appendchild($sex);  
         
        $name->appendchild($doc->createtextnode("adevy001"));  #createtextnode创建内容的子节点,然后把内容添加到节点中来  
        $namevalue->appendchild($doc->createtextnode("adevy"));  
        $sex->appendchild($doc->createtextnode(iconv("gb2312","utf-8","男"))); #注意要转码对于中文,因为xml默认为utf-8格式  
  # }     
   $doc->save("info.xml"); #保存路径eg d:/www.111cn.net  
   echo "生成成功。。。。";  
 
 
  #code by coder_apex 2007-6-15  
#自动生成一个如下的xml文件  
#  
#       <?xml version="1.0" encoding="gb2312" ? >  
#         - <root>  
#             - <info value="www.111cn.net">  
#                <name>adevy001</name>  
#                <sex>男</sex>  
#               </info>  
#           </root>

?>

本教程是利用了php domdocument函数来对xml节点 修改,增加,编辑,删除代码下面每个操作节点都是英文说明,如果你能写程序我想这些英文都能看得懂的。

//-------------------------------------------------------------------------------------

 代码如下 复制代码

function loadfile($file){
  $newfile=new domdocument();
  $newfile->validateonparse=true;
  $newfile->load($file);
 
  return $newfile;
}
function add($file, $parentname, $children){ //增加xml节点
  $xml=loadfile($file);
 
  $id=uniqid('m' . rand(1,5), true);
  $parentnode=$xml->createelement($parentname);
  $parentnode->setattribute('mid', $id);
  foreach($children as $child => $value){
    $childnode=$xml->createelement($child, $value);
    $parentnode->appendchild($childnode);
  }
  $xml->documentelement->appendchild($parentnode);
  $xml->save($file);
  return $id;
}
function delete($file, $id){//删除xml 节点
  $xml=loadfile($file);
  $ids=explode(",", $id);
  foreach ($ids as $oldnodeid){
    $oldnode=$xml->getelementbyid($oldnodeid);
    $parentnode=$oldnode->parentnode;
    $parentnode->removechild($oldnode);
  }
  $xml->save($file);
}
function edit($file, $id, $child, $value){//编辑xml 节点
  $xml=loadfile($file);
 
  $parentnode=$xml->getelementbyid($id);
  $childnode=$parentnode->childnodes->item($child);
  $textnode=$childnode->childnodes->item(0);
  $textnode->nodevalue=$value;
 
  $xml->save($file);
}
function move($file, $moveid, $refid=null){ //移动xml节点
  $xml=loadfile($file);
 
  $movenode=$xml->getelementbyid($moveid);
  $parentnode=$movenode->parentnode;
  if ($refid!=null) {
    $refnode=$xml->getelementbyid($refid);
    if(!$parentnode->issamenode($refnode->parentnode)) return false;
  }
  else $refnode=null;
  $movenode=$parentnode->removechild($movenode);
  $parentnode->insertbefore($movenode,$refnode);
 
  $xml->save($file);
}

本款教程实例是一款利用了 DOMDocument 的getElementById查询到指定的经删除节点,然后用removeChildm删除指定xml节点bi
 代码如下 复制代码
  */
  public function deletecomment($id) {
    $xml = new domdocument();
    $xml->validateonparse=true;
    $xml->loadxml($this->getcontents(true));
    $message = $xml->getelementbyid($id);
    $parentnode = $message->parentnode;
    $parentnode->removechild($message);
    $this->putcontents($xml->savexml());
  }
 
  /*
  xml 文档
 
  <?xml version="1.0" encoding="utf-8"?>
<!doctype messages [
<!element messages (message)*>
<!element message (name , website? , comment , date , user_ip? , user_agent? , spam)>
<!attlist message mid id #required>
<!element name (#pcdata)>
<!element website (#pcdata)>
<!element comment (#pcdata)>
<!element date (#pcdata)>
<!element spam (#pcdata)>
<!element user_ip (#pcdata)>
<!element user_agent (#pcdata)>
]>
<messages>
</messages>


  */

[!--infotagslink--]

相关文章

  • 基于vue-simple-uploader封装文件分片上传、秒传及断点续传的全局上传插件功能

    这篇文章主要介绍了基于vue-simple-uploader封装文件分片上传、秒传及断点续传的全局上传插件,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-23
  • php常量详细解析

    一、常量常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)。常量默认为大小写敏感。按照惯例常量标识符总是大写的。 常量名和其它任何 PHP 标签遵循...2015-10-30
  • JavaScript预解析,对象详解

    这篇文章主要介绍了JavaScript预解析,对象的的相关资料,小编觉得这篇文章写的还不错,需要的朋友可以参考下,希望能够给你带来帮助...2021-11-10
  • JS跨浏览器解析XML应用过程详解

    这篇文章主要介绍了JS跨浏览器解析XML应用过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-10-16
  • C# 如何解析获取Url参数值

    这篇文章主要介绍了C# 如何解析获取Url参数值,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2020-09-01
  • error LNK2019: 无法解析的外部符号 问题的解决办法

    error LNK2019: 无法解析的外部符号 问题的解决办法,需要的朋友可以参考一下...2020-04-25
  • JavaScript实现解析INI文件内容的方法

    这篇文章主要介绍了JavaScript实现解析INI文件内容的方法,结合实例形式分析了javascript通过自定义函数实现针对ini文件解析操作的相关处理技巧,需要的朋友可以参考下...2016-11-22
  • C#网络请求与JSON解析的示例代码

    这篇文章主要介绍了C#网络请求与JSON解析的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • 解决无法解析javax.servlet的方法

    最近在创建一个servlet时,自动生成的代码中出现servlet无法解析的提示,令我无法正常使用servlet里的方法,在对各个步骤进行查看后,发现了问题所在,需要的朋友可以参考下...2021-05-15
  • 硬核 Redis 高频面试题解析

    Redis 是一个高性能的key-value数据库。在部分场合可以对关系数据库起到很好的补充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端使用很方便...2021-06-17
  • C#域名解析简单实现方法

    这篇文章主要介绍了C#域名解析简单实现方法,可实现针对域名解析显示出主机名、IP地址、别名等功能,需要的朋友可以参考下...2020-06-25
  • C#基础知识 全面解析可空类型

    C# 2.0 中还引入了可空类型,可空类型也是值类型,只是可空类型是包括null的值类型的,下面就介绍下C#2.0中对可空类型的支持具体有哪些内容...2020-06-25
  • Intellij IDEA解析jacoco结果文件的方法

    这篇文章主要介绍了Intellij IDEA解析jacoco结果文件的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-25
  • python之pyinstaller组件打包命令和异常解析实战

    前段时间在制作小工具的时候,直接在命令行用pyinstaller工具打包成功后,启动exe可执行文件的时候各种报错, 今天,我们就分享一下踩坑经过,需要的朋友可以参考下...2021-09-20
  • JS中Eval解析JSON字符串的一个小问题

    JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧,下面通过本文给大家介绍JS中Eval解析JSON字符串的一个小问题,需要的朋友参考下吧...2016-02-23
  • 详解C#对XML、JSON等格式的解析

    这篇文章主要介绍了详解C#对XML、JSON等格式的解析,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。...2020-06-25
  • php中SimpleXMLElement 对象转换为数组

    PHP 提供了 simplexml_load_string 方法用来解析 XML 格式的字符串,并返回 SimpleXMLElement 对象。不过一般数组是更为适用的,所以也会有转换为普通数组的需求,这个方法...2016-11-25
  • 动态webservice调用接口并读取解析返回结果

    webservice的 发布一般都是使用WSDL(web service descriptive language)文件的样式来发布的,在WSDL文件里面,包含这个webservice暴露在外面可供使用的接口。今天我们来详细讨论下如何动态调用以及读取解析返回结果...2020-06-25
  • C#实现的优酷真实视频地址解析功能(2014新算法)

    这篇文章主要介绍了C#实现的优酷真实视频地址解析功能(2014新算法),本文在当前环境下是有效的,因为优酷之前更新了算法,需要的朋友可以参考下...2020-06-25
  • C#如何解析http报文

    这篇文章如果讲解了用C#如何解析http报文,要解析http报文,需要哪些操作呢?下面小编给大家整理相关资料,需要的朋友可以参考下...2020-06-25