Home Backend Development PHP Tutorial Examples of four methods for php to parse xml files

Examples of four methods for php to parse xml files

Jul 25, 2016 am 08:59 AM

  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 arrayn";
  6. print_r($index);
  7. echo "nVals arrayn";
  8. print_r($vals);
  9. ?>
复制代码

输出:

  1. $xml = '

  2. note1extra1
  3. note2
  4. note3extra3
  5. ';

  6. $p = xml_parser_create();

  7. xml_parse_into_struct($p, $xml, $values, $tags);
  8. xml_parser_free($p);
  9. $result = array();
  10. //下面的遍历方式有bug隐患
  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. ?>

复制代码

要是按照上面那种方式遍历,会得到错误的结果(extra3跑到第二个para里了)。所以要以一种比较严谨的方式遍历:

  1. $result = array();
  2. $paraTagIndexes = $tags['PARA'];
  3. $paraCount = count($paraTagIndexes);
  4. for($i = 0; $i < $paraCount; $i += 2) {
  5. $para = array();
  6. //遍历para标签对之间的所有值
  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. ?>
复制代码

其实,平时很少用xml_parse_into_struct函数,所以上面所谓“严谨”的代码保不齐还会有其他情况下的bug。

xml_set_element_handler

这种方式是为parser设置处理元素起始、元素终止的回调函数。 配套的还有xml_set_character_data_handler用来为parser设置数据的回调函数。 这种方式写的代码比较清晰,利于维护。 例子:

  1. $xml = <<

  2. note1extra1
  3. note2
  4. note3extra3
  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 more lines of code, it has clear ideas and better readability, 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 using older versions. For PHP5 environment, give priority to the following method.

2,SimpleXML

SimpleXML is a set of simple and easy-to-use XML tools provided after PHP5. It can convert XML into objects that are convenient for processing, and can also organize and generate XML data. However, it does not apply to xml containing namespace, and the xml must be well-formed. It provides three methods: simplexml_import_dom, simplexml_load_file, simplexml_load_string. The function name intuitively explains the function. All three functions return SimpleXMLElement objects, and data is read/added through SimpleXMLElement operations.

  1. $string = <<

  2. login< ;/cmd>
  3. imdonkey
  4. XML;

  5. $xml = simplexml_load_string($string);

  6. print_r($xml);
  7. $login = $xml->login;//What is returned here is still a SimpleXMLElement object
  8. print_r($login);
  9. $login = (string) $xml->login;//When doing data comparison, pay attention to First force conversion
  10. print_r($login);
  11. ?>

Copy code

The advantage of SimpleXML is that it is simple to develop, but the disadvantage is that it will load the entire xml into the memory before processing. Therefore, it may be difficult to parse an xml document with a lot of content. If you are reading small files and the xml does not contain namespace, then SimpleXML is a good choice.

3,XMLReader XMLReader is also an extension after PHP5 (installed by default after 5.1). It moves in the document flow like a cursor and stops at each node. It is very flexible to operate. It provides fast and non-cached streaming access to input, and can read a stream or document, allowing the user to extract data from it, and skip records that are not meaningful to the application. 1 2 Next Page Last Page



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles