This article mainly introduces PHP based on the XmlWriter operation of XML method, combined with instance form analysis of PHP using XmlWriter to generate and parse XML data operation skills, the need for friends can refer to the following
Then this time yesterday to learn a way to read and write XML, which is mainly around XmlWriter and XmlReader. The former is used to generate XML, while the latter is used to read and parse the XML. No more talking.
1. Generating an XML file or string
<?php header ("content-type:text/html; Charset=utf-8 "); $xml =new XMLWriter (); $xml->openuri ("Php://output"); Set the output, if you do not need to save the file to use the above is commented out that sentence $xml->openuri ("Stu2.xml"); Set the indentation string, which is set to an empty string (this sentence and the following setintent can also not) $xml->setindentstring ("); $xml->setindent (TRUE); The XML document begins $xml->startdocument (' 1.0 ', ' utf-8 '); Create the root node $xml->startelement ("Studentinfo"); $xml->startelement ("Item"); Add attribute $xml->writeattribute ("type", "1"); $xml->startelement ("id"); $xml->text ("01"); $xml->endelement (); $xml->startelement ("name"); $xml->text ("ylamproductions June"); $xml->endelement (); $xml->endelement (); $xml->endelement (); $xml->enddocument (); Header ("Content-type:text/xml"); Gets the XML string in the buffer//echo $xml->outputmemory ();? >
This approach is characterized by the need for a endelement,xml after each label is finished to close the document. There's a "layered wrap" sensation.
2. Parsing xml
<?php header ("content-type:text/html; Charset=utf-8 "); $xml =new XMLReader ();//load XML file, if string is directly using XML method $xml->open ("Student.xml");//start reading XML while ($xml->read ()) { get the text node or attribute if ($xml->nodetype = = Xmlreader::element && $xml->localname = = ' item ') based on node type and element name { print $xml->getattribute ("id"). "</br>"; } if ($xml->nodetype = = Xmlreader::element && $xml->localname = = ' name ') { //move pointer to next node $xml Read (); Gets the value of the text node print $xml->value. " </br> "; } if ($xml->nodetype = = Xmlreader::element && $xml->localname = = ' age ') { $xml->read (); Print $xml->value. " </br> "; } }?>
This method of parsing XML is more efficient, if some places do not understand the proposal to review the PHP development manual
The content of the parsed file is as follows
<?xml version= "1.0" encoding= "Utf-8"? ><usersinfo><item id= "" ><name> William Feng </name>< Age>30</age></item><item id= "><name> Wilber" </name><age>29</age>< /item></usersinfo>
Here are the results that are parsed out
Related recommendations:
Detailed example code for writing XML using XmlWriter
XML operation of PHP extension (v)--XMLWriter
PrintWriter simple sample code for PHP XMLWriter class RSS output