How PHP processes XML file instances

Source: Internet
Author: User
Tags php print processing instruction
What is the essence of XML? This is what we describe based on information, which can reflect the logical relationship between data and information, and ensure that files are easy to use and easy to search for custom tags. your XML file follows the so-called ldquo; well-formed rdquo; requires various syntaxes... What is the essence of XML?

This is what we describe based on information, which can reflect the logical relationship between data and information, and ensure that files are easy to use and easy to search for custom tags.

Your XML file follows the syntax rules required by the so-called "good form". in a complete sense, an XML file should not only be "good form ", it should also be an XML file with these custom tags "valid.

An XML file must comply with the rules defined in Document Type Definition (DTD). DTD is actually a product of the concept of "meta tag, it describes the syntax and vocabulary of a markup language, that is, it defines the overall structure of the file and the syntax of the file. In short, DTD specifies the details of all the rules that a syntax analyzer needs to know to explain a "valid" XML file.

How to write an XML file

1. the first line

2. there must be an outermost tag

3. XML tags are case-insensitive and can be used in Chinese. what is the start mark and what is the end mark?

4. all XML tags must end

5. all attribute values must use quotation marks.

6. the layers should be clear

7. the same tag cannot be nested.

8. entities can be used &;

9. Notes

10.

How PHP processes XML files

In fact, using the xml parsing function of php, processing xml documents is tantamount to processing files, as long as you write several processing functions according to your specific needs, everything is fine, understand the reading of xml files, therefore, generating xml files is not a problem. pay attention to the encoding and writing specifications of xml files.

The following is a classic example in the manual. the code is as follows:

 $ Data";}// Processing instruction (PI) processor parameter processing function PIHandler ($ parser, $ target, $ data) {switch (strtolower ($ target )) {case "php": global $ parser_file; // If the parsed document is "trusted", we say it is safe // to execute PHP code inside it. if not, display the code // instead. if (trustedFile ($ parser_file [$ parser]) {eval ($ data);} else {printf ("Untrusted PHP code:% S", Htmlspecialchars ($ data) ;}break ;}// default processing handle function defaultHandler ($ parser, $ data) {if (substr ($ data, 0, 1) = "&" & substr ($ data,-1, 1) = ";") {// determines whether the data is an external entity. pay attention to this method. Printf ('% s', htmlspecialchars ($ data);} else {printf (' % s', htmlspecialchars ($ data ));}} // external entity processing handle function externalEntityRefHandler ($ parser, $ openEntityNames, $ base, $ systemId, $ publicId) {if ($ systemId) {if (! List ($ parser, $ fp) = new_xml_parser ($ systemId) {printf ("cocould not open entity % s at % sn", $ openEntityNames, $ systemId ); return false;} while ($ data = fread ($ fp, 4096) {if (! Xml_parse ($ parser, $ data, feof ($ fp) {printf ("XML error: % s at line % d while parsing entity % sn ", xml_error_string (xml_get_error_code ($ parser), evaluate ($ parser), $ openEntityNames); xml_parser_free ($ parser); return false ;}} xml_parser_free ($ parser); return true ;} return false;} // xml analyzer. Function new_xml_parser ($ file) {global $ parser_file; $ xml_parser = xml_parser_create (); // Create an XML parser. This function returns the interpreter's operation handle. Xml_parser_set_option ($ xml_parser, XML_OPTION_CASE_FOLDING, 1); // you can specify whether to use case-sensitive folding and target code xml_set_element_handler ($ xml_parser, "startElement", "endElement "); // create a starting and ending element processor, bool xml_set_character_data_handler ($ xml_parser, "characterData"); // create a character data processor, bool handler ($ xml_parser, "PIHandler "); // Create a processing instruction (PI) processor xml_set_default_handler ($ xml_parser, "defaultHandler"); // default processor xml_se T_external_entity_ref_handler ($ xml_parser, "externalEntityRefHandler"); // external entity pointing to the processor if (! ($ Fp = @ fopen ($ file, "r") {return false;} if (! Is_array ($ parser_file) {settype ($ parser_file, "array"); // Set the file processing variable to the array type} $ parser_file [$ xml_parser] = $ file; //? Assign a file name value to the array where the interpreter's operation handle is the index? (The Interpreter handle is returned as a resource record) // echo "parser ="; // print_r ($ parser_file); // echo"
$ Xml_parser "; // echo" "; return array ($ xml_parser, $ fp); // The Operation handle of the interpreter and the handle of the file to be analyzed} if (! (List ($ xml_parser, $ fp) = new_xml_parser ($ file) {die ("cocould not open XML input");} print"
"; While ($ data = fread ($ fp, 4096) {if (! Xml_parse ($ xml_parser, $ data, feof ($ fp) {// conditional assignment is used here. If processing is executed when the conditional expression is invalid. Otherwise, it is skipped. Die (sprintf ("XML error: % s at line % dn", xml_error_string (xml_get_error_code ($ xml_parser), xml_get_current_line_number ($ xml_parser )));}} // open source code phprm.com print"
"; Print" parse completen "; xml_parser_free ($ xml_parser );

Xmltest. xml file. the instance code is as follows:

  
   
  Title  
     
       
               
     
      
        A1
      
      
        B1
      
      
        C1
      
           
     
      
        A2
      
      
        C2
      
           
     
      
        A3
      
      
        B3
      
      
        C3
      
              
       
     
    
     
   About this Document   
       
        
      
   
    
  

Another example is to process an xml file into a php array. the code is as follows:

 $ V) $ this-> $ k = $ aa [$ k] ;}} function readDatabase ($ filename) {// read the xml database of aminoacids $ data = implode ("", file ($ filename); // read the entire article into the array first, connect the array to a string and assign it to $ data. $ parser = xml_parser_create (); xml_parser_set_option ($ parser, XML_OPTION_CASE_FOLDING, 0); // xml_parser_set_option ($ parser, parser, 1) without case folding; aggregate ($ parser, $ data, $ values, $ tags); // parses XML data into an array. Parse the XML file to two corresponding arrays. The // $ tags parameter contains pointers pointing to the corresponding values in the $ values array. The last two array parameters can be passed to the function by pointers. Xml_parser_free ($ parser); // loop through the structures // for specific applications (for different xml files, modify the loop structure here to get a specific array. Foreach ($ tags as $ key => $ val) {if ($ key = "molecule") {$ molranges = $ val; // each contiguous pair of array entries are the // lower and upper range for each molecule definition for ($ I = 0; $ I <count ($ molranges ); $ I + = 2) {$ offset = $ molranges [$ I] + 1; $ len = $ molranges [$ I + 1]-$ offset; $ tdb [] = parseMol (array_slice ($ values, $ offset, $ len) ;}} else {continue ;}// echo "values is :"; // print_r ($ values); // echo ""; return array ($ tdb, $ values);} function parseMol ($ mvalues) {for ($ I = 0; $ I <count ($ mvalues); $ I ++) $ mol [$ mvalues [$ I] ["tag"] = $ mvalues [$ I] ["value"]; // echo "after parsemol :"; // print_r ($ mol); // echo ""; return new AminoAcid ($ mol);} $ db = readDatabase ("moldb. xml "); echo" ** Database of AminoAcid objects: n "; // echo" readdatabase: "; print_r ($ db [0]); // echo ""; $ s = parseMol ($ db [1]);

The code is as follows:

      
          
  
   Alanine
           
  
   ala
           
  A         
  
   hydrophobic
       
      
          
  
   Lysine
           
  
   lys
           
  K         
  
   charged
       
   

Tutorial link:

Reprint at will ~ However, please keep the tutorial address★

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.