This article mainly introduces the PHP implementation based on SimpleXML generation and parsing of XML methods, combined with a complete example of PHP using SimpleXML to generate and parse XML format data specific operation skills, the need for friends can refer to the next
XML does not explain much, PHP also provides a way to manipulate XML, PHP operation XML can have a variety of ways such as Domdocment,simplexml,xmlwriter, the simplest of which should be simplexml, This time, say simplexml. How to read and parse an XML file or string
1. Generating 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", "William Feng"); $item->addchild ("Age", "30"); $item 2= $xml->addchild ("item"); $item 2->addchild ("name", "Wilber Cypress"); $item 2->addchild ("Age", "29"); $item 2->addattribute ("id", "02"); Header ("Content-type:text/xml"); echo $xml->asxml (); $xml->asxml ("Student.xml");? >
The most important thing to generate XML is addchild,addattribute,asxml three methods, if you just generate XML files that header can not, the following is the browser display results
Isn't it easy?
2. simplexml parsing an XML file or string
<?php header ("content-type:text/html; Charset=utf-8 "); $xml =simplexml_load_file ("Userinfo.xml"); Get the subkey under the root node for ($i =0, $i <count ($xml->children ()), $i + +) { foreach ($xml->children () [$i] as $ by children Key = $value) { echo "$key: $value". " <br/> "; } }?>
The above method is suitable for parsing the XML file, if it is an XML string to change the simplexml_load_file to simplexml_load_string, children used to get the root node or child nodes, The obtained node is an array of direct traversal necessary when the filter condition is added, the following is the result of parsing
By the way, I'm pasting my XML file.
<?xml version= "1.0" encoding= "UTF-8"?><usersinfo> <item> <name> Wilber Kashiwa </name> <address> Shanghai Pudong New Area </address> <song> Happy worship </song> </item> <item> <name > Jolin Tsai </name> <address> Shanghai Xuhui </address> <song> exclusive Myths </song> </item> </UsersInfo>