php 使用expat方式解析xml文件操作示例

这篇文章主要介绍了php 使用expat方式解析xml文件操作,结合实例形式分析了PHP使用expat方式解析xml文件具体步骤与相关操作技巧,需要的朋友可以参考下。

本文实例讲述了php 使用expat方式解析xml文件操作,分享给大家供大家参考,具体如下:

test.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <notes>
  3. <note>
  4. <to>George</to>
  5. <from>John</from>
  6. <heading>Reminder</heading>
  7. <body>Don't forget the meeting!</body>
  8. </note>
  9. <note>
  10. <to>George2</to>
  11. <from>John2</from>
  12. <heading>Reminder2</heading>
  13. <body>Don't forget the meeting!2</body>
  14. </note>
  15. <instances>
  16. <instance st="192.168.234.121" />
  17. <instance st="192.168.234.28" />
  18. </instances>
  19. </notes>

PHP文件:

  1. <?php
  2. // Initialize the XML parser
  3. $parser = xml_parser_create();
  4. // Function to use at the start of an element
  5. function start($parser, $element_name, $element_attrs)
  6. {
  7. switch ($element_name) {
  8. case "NOTE":
  9. echo "-- Note --<br />";
  10. break;
  11. case "TO":
  12. echo "To: ";
  13. break;
  14. case "FROM":
  15. echo "From: ";
  16. break;
  17. case "HEADING":
  18. echo "Heading: ";
  19. break;
  20. case "BODY":
  21. echo "Message: ";
  22. }
  23. }
  24. // Function to use at the end of an element
  25. function stop($parser, $element_name)
  26. {
  27. echo "<br />";
  28. }
  29. // Function to use when finding character data
  30. function char($parser, $data)
  31. {
  32. echo $data;
  33. }
  34. // Specify element handler
  35. xml_set_element_handler($parser, "start", "stop");
  36. // Specify data handler
  37. xml_set_character_data_handler($parser, "char");
  38. // Open XML file
  39. // $fp = fopen("test.xml", "r");
  40. // Read data
  41. // while ($data = fread($fp, 10)) {
  42. // xml_parse($parser, $data, feof($fp)) or die(sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));
  43. // }
  44. // fclose($fp);
  45. $data = file_get_contents("test.xml");
  46. xml_parse($parser, $data) or die(sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));
  47. // Free the XML parser
  48. xml_parser_free($parser);
  49. ?>

运行结果:

  1. -- Note --
  2. To: George
  3. From: John
  4. Heading: Reminder
  5. Message: Don't forget the meeting!
  6. -- Note --
  7. To: George2
  8. From: John2
  9. Heading: Reminder2
  10. Message: Don't forget the meeting!2