Home Backend Development PHP Tutorial Four methods for php to parse xml

Four methods for php to parse xml

Jul 15, 2016 pm 01:24 PM
php

XML processing is often encountered in the development process, and PHP also has rich support for it. This article only briefly explains some of the parsing technologies, including: Xml parser, SimpleXML, XMLReader, DOMDocument.

1. XML Expat Parser:

XML Parser uses the Expat XML parser. Expat is an event-based parser that treats XML documents as a series of events. When an event occurs, it calls a specified function to handle it. Expat is a validation-free parser that ignores any DTD linked to the document. However, if the document is not in good form, it will end up with an error message. Because it is event-based and has no validation, Expat is fast and suitable for web applications.

The advantage of XML Parser is its good performance, because it does not load the entire xml document into memory and then process it, but processes it while parsing it. But precisely because of this, it is not suitable for those who need to dynamically adjust the XML structure or perform complex operations based on the XML context structure. If you just want to parse and process a well-structured xml document, then it can complete the task well. It should be noted that XML Parser only supports three encoding formats: US-ASCII, ISO-8859-1 and UTF-8. If your xml data is in other encodings, you need to convert it to one of the above three first.
There are generally two commonly used parsing methods for XML Parser (actually two functions): xml_parse_into_struct and xml_set_element_handler.


xml_parse_into_struct

This method parses the xml data into two arrays:
index array - contains a pointer to the location of the value in the Value array
value Array - contains data from the parsed XML

These two arrays are a bit cumbersome to describe textually, so let’s look at an example (from the official php documentation)

1

2

3

4

5

6

7

8

$simple = "<para><note>simple note</note></para>";

$p = xml_parser_create();

xml_parse_into_struct($p, $simple, $vals, $index);

xml_parser_free($p);

echo "Index array\n";

print_r($index);

echo "\nVals array\n";

print_r($vals);

Copy after login

Output:
Index array
Array
(
[PARA] => 🎜>
[NOTE] => Array
(
[0] => 1
)

)


Vals array
Array
(
[0] => Array

(

[tag] => PARA
[type] => open
[level] => 1
)

[1] => Array
(
[tag] => NOTE
[type] => complete

[level] => 2

                         ] => simple note
)

[2] => Array
(
) [tag] => PARA
[type] => close

[level] => 1

)
)

The index array uses the label name as key, and the corresponding value is an array, which includes the position of all this label in the value array. Then through this position, find the value corresponding to this label.

If the format of each set of data in xml is different and cannot be completely unified, then you should pay attention when writing code, you may get wrong results. For example, the following example:

If you traverse in the above way, the code seems simple, but there are hidden dangers. The most fatal thing is that you get the wrong result (extra3 runs into the second para) . So we need to traverse in a more rigorous way:

In fact, I rarely use the xml_parse_into_struct function, so if the so-called "rigorous" code above is not preserved, there will be bugs in other situations. - -|

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$xml = &#39;

<infos>

<para><note>note1</note><extra>extra1</extra></para>

<para><note>note2</note></para>

<para><note>note3</note><extra>extra3</extra></para>

</infos>

&#39;;

 

$p = xml_parser_create();

xml_parse_into_struct($p, $xml, $values, $tags);

xml_parser_free($p);

$result = array();

//下面的遍历方式有bug隐患

for ($i=0; $i<3; $i++) {

  $result[$i] = array();

  $result[$i]["note"] = $values[$tags["NOTE"][$i]]["value"];

  $result[$i]["extra"] = $values[$tags["EXTRA"][$i]]["value"];

}

print_r($result);

Copy after login
xml_set_element_handler

This method is to set the callback function for parser to handle the start and end of elements. Also included is the callback function xml_set_character_data_handler used to set data for the parser. The code written in this way is clearer and easier to maintain.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$result = array();

$paraTagIndexes = $tags[&#39;PARA&#39;];

$paraCount = count($paraTagIndexes);

for($i = 0; $i < $paraCount; $i += 2) {

  $para = array();

  //遍历para标签对之间的所有值

  for($j = $paraTagIndexes[$i]; $j < $paraTagIndexes[$i+1]; $j++) {

    $value = $values[$j][&#39;value&#39;];

    if(empty($value)) continue;

 

    $tagname = strtolower($values[$j][&#39;tag&#39;]);

    if(in_array($tagname, array(&#39;note&#39;,&#39;extra&#39;))) {

      $para[$tagname] = $value;

    }

  }

  $result[] = $para;

}

Copy after login

Example:

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 Not very flexible. XML Parser supports PHP4 and is suitable for systems using older versions. For PHP5 environment, give priority to the following method.

2. SimpleXML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

$xml = <<<XML

<infos>

<para><note>note1</note><extra>extra1</extra></para>

<para><note>note2</note></para>

<para><note>note3</note><extra>extra3</extra></para>

</infos>

XML;

 

$result = array();

$index = -1;

$currData;

 

function charactor($parser, $data) {

  global $currData;

  $currData = $data;

}

 

function startElement($parser, $name, $attribs) {

  global $result, $index;

  $name = strtolower($name);

  if($name == &#39;para&#39;) {

    $index++;

    $result[$index] = array();

  }

}

 

function endElement($parser, $name) {

  global $result, $index, $currData;

  $name = strtolower($name);

  if($name == &#39;note&#39; || $name == &#39;extra&#39;) {

    $result[$index][$name] = $currData;

  }

}

 

$xml_parser = xml_parser_create();

xml_set_character_data_handler($xml_parser, "charactor");

xml_set_element_handler($xml_parser, "startElement", "endElement");

if (!xml_parse($xml_parser, $xml)) {

  echo "Error when parse xml: ";

  echo xml_error_string(xml_get_error_code($xml_parser));

}

xml_parser_free($xml_parser);

 

print_r($result);

Copy after login

SimpleXML是PHP5后提供的一套简单易用的xml工具集,可以把xml转换成方便处理的对象,也可以组织生成xml数据。不过它不适用于包含namespace的xml,而且要保证xml格式完整(well-formed)。它提供了三个方法:simplexml_import_dom、simplexml_load_file、simplexml_load_string,函数名很直观地说明了函数的作用。三个函数都返回SimpleXMLElement对象,数据的读取/添加都是通过SimpleXMLElement操作。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$string = <<<XML

<?xml version=&#39;1.0&#39;?>

<document>

  <cmd>login</cmd>

  <login>imdonkey</login>

</document>

XML;

 

$xml = simplexml_load_string($string);

print_r($xml);

$login = $xml->login;//这里返回的依然是个SimpleXMLElement对象

print_r($login);

$login = (string) $xml->login;//在做数据比较时,注意要先强制转换

print_r($login);

Copy after login

SimpleXML的优点是开发简单,缺点是它会将整个xml载入内存后再进行处理,所以在解析超多内容的xml文档时可能会力不从心。如果是读取小文件,而且xml中也不包含namespace,那SimpleXML是很好的选择。


3。 XMLReader

XMLReader也是PHP5之后的扩展(5.1后默认安装),它就像游标一样在文档流中移动,并在每个节点处停下来,操作起来很灵活。它提供了对输入的快速和非缓存的流式访问,可以读取流或文档,使用户从中提取数据,并跳过对应用程序没有意义的记录。
以一个利用google天气api获取信息的例子展示下XMLReader的使用,这里也只涉及到一小部分函数,更多还请参考官方文档。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

$xml_uri = &#39;http://www.google.com/ig/api?weather=Beijing&hl=zh-cn&#39;;

$current = array();

$forecast = array();

 

$reader = new XMLReader();

$reader->open($xml_uri, &#39;gbk&#39;);

while ($reader->read()) {

  //get current data

  if ($reader->name == "current_conditions" && $reader->nodeType == XMLReader::ELEMENT) {

    while($reader->read() && $reader->name != "current_conditions") {

      $name = $reader->name;

      $value = $reader->getAttribute(&#39;data&#39;);

      $current[$name] = $value;

    }

  }

 

  //get forecast data

  if ($reader->name == "forecast_conditions" && $reader->nodeType == XMLReader::ELEMENT) {

    $sub_forecast = array();

    while($reader->read() && $reader->name != "forecast_conditions") {

      $name = $reader->name;

      $value = $reader->getAttribute(&#39;data&#39;);

      $sub_forecast[$name] = $value;

    }

    $forecast[] = $sub_forecast;

  }

}

$reader->close();

Copy after login

XMLReader和XML Parser类似,都是边读边操作,较大的差异在于SAX模型是一个“推送”模型,其中分析器将事件推到应用程序,在每次读取新节点时通知应用程序,而使用XmlReader的应用程序可以随意从读取器提取节点,可控性更好。
由于XMLReader基于libxml,所以有些函数要参考文档看看是否适用于你的libxml版本。

4。 DOMDocument

DOMDocument还是PHP5后推出的DOM扩展的一部分,可用来建立或解析html/xml,目前只支持utf-8编码。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

$xmlstring = <<<XML

<?xml version=&#39;1.0&#39;?>

<document>

  <cmd attr=&#39;default&#39;>login</cmd>

  <login>imdonkey</login>

</document>

XML;

 

$dom = new DOMDocument();

$dom->loadXML($xmlstring);

print_r(getArray($dom->documentElement));

 

function getArray($node) {

  $array = false;

 

  if ($node->hasAttributes()) {

    foreach ($node->attributes as $attr) {

      $array[$attr->nodeName] = $attr->nodeValue;

    }

  }

 

  if ($node->hasChildNodes()) {

    if ($node->childNodes->length == 1) {

      $array[$node->firstChild->nodeName] = getArray($node->firstChild);

    } else {

      foreach ($node->childNodes as $childNode) {

      if ($childNode->nodeType != XML_TEXT_NODE) {

        $array[$childNode->nodeName][] = getArray($childNode);

      }

    }

  }

  } else {

    return $node->nodeValue;

  }

  return $array;

}

Copy after login

从函数名上看感觉跟JavaScript很像,应该是借鉴了一些吧。DOMDocument也是一次性将xml载入内存,所以内存问题同样需要注意。PHP提供了这么多的xml处理方式,开发人员在选择上就要花些时间了解,选择适合项目需求及系统环境、又便于维护的方法。

转 


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles