怎么在PHP中使用SimpleXML生成和解析xml

怎么在PHP中使用SimpleXML生成和解析xml

怎么在PHP中使用SimpleXML生成和解析xml?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

1. 生成xml字符串和文件

<?php
 header("Content-type: text/html; charset=utf-8");
 $xml=new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><UsersInfo />');
 $item=$xml->addchild("item");
 $item->addchild("name","冯绍峰");
 $item->addchild("age","30");
 $item2=$xml->addchild("item");
 $item2->addchild("name","潘玮柏");
 $item2->addchild("age","29");
 $item2->addAttribute("id","02");
 header("Content-type: text/xml");
 echo $xml->asXml();
 $xml->asXml("student.xml");
?>

生成xml最重要的就是addchild,addAttribute,asXml三个方法,如果只是单纯生成xml文件的话那个header可以不要,下面是浏览器的显示结果

 怎么在PHP中使用SimpleXML生成和解析xml

是不是很简单呢

2. simplexml解析xml文件或字符串

<?php
 header("Content-type: text/html; charset=utf-8");
 $xml=simplexml_load_file("UserInfo.xml");
 //通过children取得根节点下面的子项
 for($i=0;$i<count($xml->children());$i++){
   foreach ($xml->children()[$i] as $key => $value ) {
    echo "$key:$value"."<br/>";
   }
 }
?>

上面的方法适合解析xml文件,如果是xml字符串就把simplexml_load_file改为simplexml_load_string就可以了,children用于取得根节点或者子节点,取得的节点是一个数组直接遍历必要的时候加上过滤条件就可以了,下面是解析的结果

 怎么在PHP中使用SimpleXML生成和解析xml

顺便把我的xml文件贴出来

<?xml version="1.0" encoding="UTF-8"?>
<UsersInfo>
 <item>
   <name>潘玮柏</name>
   <address>上海市浦东新区</address>
   <song>快乐崇拜</song>
 </item>
 <item>
   <name>蔡依林</name>
   <address>上海市徐汇区</address>
   <song>独占神话</song>
 </item>
</UsersInfo>

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。