Home > Article > Backend Development > Introduction to the use of SimpleXML for PHP xml parsing and generation
Xml will not be explained much. PHP also provides methods to operate XML. PHP can operate XML in many ways, such as domdocment, simplexml, xmlwriter, etc. The simplest one should be simplexml. This time I will talk about simplexml. How to read and parse xml files or strings
1. Generate xml strings and files
<?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"); ?>
The most important methods for generating xml are addchild, addAttribute, and asXml. If you just generate an xml file, you don’t need the header. The following is the display result of the browser
Isn’t it very simple?
2. simplexml parses xml files or strings
<?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/>"; } } ?>
above The method is suitable for parsing xml files. If it is an xml string, just change simplexml_load_file to simplexml_load_string. Children is used to obtain the root node or child node. The obtained node is an array and can be traversed directly. If necessary, just add filter conditions. , the following is the result of the analysis
By the way, post my xml file
<?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>
Generally speaking, the operation It's so concise.
The above is the detailed content of Introduction to the use of SimpleXML for PHP xml parsing and generation. For more information, please follow other related articles on the PHP Chinese website!