Example of four methods for parsing xml files in php

Source: Internet
Author: User
Example of four methods for parsing xml files in php

  1. $ Simple =" Simple note ";
  2. $ P = xml_parser_create ();
  3. Xml_parse_into_struct ($ p, $ simple, $ vals, $ index );
  4. Xml_parser_free ($ p );
  5. Echo "Index array \ n ";
  6. Print_r ($ index );
  7. Echo "\ nVals array \ n ";
  8. Print_r ($ vals );
  9. ?>

Output:

  1. $ Xml ='

  2. Note1 Extra1
  3. Note2
  4. Note3 Extra3
  5. ';

  6. $ P = xml_parser_create ();

  7. Xml_parse_into_struct ($ p, $ xml, $ values, $ tags );
  8. Xml_parser_free ($ p );
  9. $ Result = array ();
  10. // The following traversal method has bugs
  11. For ($ I = 0; $ I <3; $ I ++ ){
  12. $ Result [$ I] = array ();
  13. $ Result [$ I] ["note"] = $ values [$ tags ["NOTE"] [$ I] ["value"];
  14. $ Result [$ I] ["extra"] = $ values [$ tags ["EXTRA"] [$ I] ["value"];
  15. }
  16. Print_r ($ result );
  17. ?>

If we traverse through the above method, we will get the wrong result (extra3 ran to the second para ). Therefore, we need to traverse in a more rigorous way:

  1. $ Result = array ();

  2. $ ParaTagIndexes = $ tags ['para'];
  3. $ ParaCount = count ($ paraTagIndexes );
  4. For ($ I = 0; $ I <$ paraCount; $ I + = 2 ){
  5. $ Para = array ();
  6. // Traverse all values between para tag pairs
  7. For ($ j = $ paraTagIndexes [$ I]; $ j <$ paraTagIndexes [$ I + 1]; $ j ++ ){
  8. $ Value = $ values [$ j] ['value'];
  9. If (empty ($ value) continue;

  10. $ Tagname = strtolower ($ values [$ j] ['tag']);

  11. If (in_array ($ tagname, array ('note', 'Extra '))){
  12. $ Para [$ tagname] = $ value;
  13. }
  14. }
  15. $ Result [] = $ para;
  16. }
  17. ?>

In fact, the xml_parse_into_struct function is rarely used at ordinary times, so the above so-called "rigorous" code is not properly maintained and there will be bugs in other situations.

Xml_set_element_handler

This method sets a callback function for parser to process the start and end of an element. Xml_set_character_data_handler is used to set the data callback function for parser. The code written in this way is clear and easy to maintain. Example:

  1. $ Xml = <

  2. Note1 Extra1
  3. Note2
  4. Note3 Extra3
  5. XML;

  6. $ Result = array ();

  7. $ Index =-1;
  8. $ CurrData;

  9. Function charactor ($ parser, $ data ){

  10. Global $ currData;
  11. $ CurrData = $ data;
  12. }

  13. Function startElement ($ parser, $ name, $ attribs ){

  14. Global $ result, $ index;
  15. $ Name = strtolower ($ name );
  16. If ($ name = 'para '){
  17. $ Index ++;
  18. $ Result [$ index] = array ();
  19. }
  20. }

  21. Function endElement ($ parser, $ name ){

  22. Global $ result, $ index, $ currData;
  23. $ Name = strtolower ($ name );
  24. If ($ name = 'note' | $ name = 'Extra '){
  25. $ Result [$ index] [$ name] = $ currData;
  26. }
  27. }

  28. $ Xml_parser = xml_parser_create ();

  29. Xml_set_character_data_handler ($ xml_parser, "charactor ");
  30. Xml_set_element_handler ($ xml_parser, "startElement", "endElement ");
  31. If (! Xml_parse ($ xml_parser, $ xml )){
  32. Echo "Error when parse xml :";
  33. Echo xml_error_string (xml_get_error_code ($ xml_parser ));
  34. }
  35. Xml_parser_free ($ xml_parser );

  36. Print_r ($ result );

  37. ?>

It can be seen that although the set handler method has many lines of code, its ideas are clear and its readability is better, but its performance is slightly slower than the first method, and its flexibility is not strong. XML Parser supports PHP4 and is suitable for systems of earlier versions. For the PHP5 environment, consider the following methods first.

2, SimpleXML

SimpleXML is a simple and easy-to-use xml tool set provided by PHP5. it can convert xml into easy-to-process objects and organize and generate xml data. However, it does not apply to xml that contains namespace, and must ensure that the xml format is complete (well-formed ). It provides three methods: simplexml_import_dom, simplexml_load_file, and simplexml_load_string. the function name intuitively illustrates the function's role. All three functions return SimpleXMLElement objects, and data reading/adding is performed through SimpleXMLElement.

  1. $ String = <

  2. Login
  3. Imdonkey
  4. XML;

  5. $ Xml = simplexml_load_string ($ string );

  6. Print_r ($ xml );
  7. $ Login = $ xml-> login; // The Returned result is still a SimpleXMLElement object.
  8. Print_r ($ login );
  9. $ Login = (string) $ xml-> login; // when comparing data, be sure to forcibly convert
  10. Print_r ($ login );
  11. ?>

SimpleXML is easy to develop. Its disadvantage is that it loads the entire xml into the memory before processing. Therefore, it may not be able to resolve xml documents with too much content. If you want to read small files and xml does not contain namespace, SimpleXML is a good choice.

3. XMLReaderXMLReader is also an extension after PHP5 (installed by default after 5.1). It moves in the document stream just like a cursor and stops at each node. The operation is flexible. It provides fast and non-cache stream access to the input, and can read streams or documents, allowing users to extract data from it and skip records that are meaningless to the application.12. Next page

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.