search
HomeBackend DevelopmentPHP TutorialFour simple methods for parsing xml in php (with examples)

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 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. 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 the data from the parsed XML

It’s a bit troublesome to describe these two arrays textually, so let’s look at an example (from PHP official documentation)

$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);

Output:

Index array
Array
(
  [PARA] => Array
    (
      [0] => 0
      [1] => 2
    )
 
  [NOTE] => Array
    (
      [0] => 1
    )
)
 
Vals array
Array
(
  [0] => Array
    (
      [tag] => PARA
      [type] => open
      [level] => 1
    )
 
  [1] => Array
    (
      [tag] => NOTE
      [type] => complete
      [level] => 2
      [value] => simple note
    )
 
  [2] => Array
    (
      [tag] => PARA
      [type] => close
      [level] => 1
    )
)

The index array has a label named key, and the corresponding value is an array, which includes The position of all this tags 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:

$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);

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

$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;
}

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. - -|
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.

Example:

$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);


It can be seen that although the set handler method has many 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.

$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);

The advantage of SimpleXML is that it is simple to develop. The disadvantage is that it loads the entire xml into the memory before processing, so it may not be able 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.
An example of using the Google Weather API to obtain information shows the use of XMLReader. Only a small number of functions are involved here. For more information, please refer to the official documentation.

$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();

XMLReader is similar to XML Parser, both operate while reading. The big difference is that the SAX model is a "push" model, in which the analyzer pushes events to the application and notifies the application each time a new node is read. program, while the application using XmlReader can extract nodes from the reader at will, with better controllability.
Since XMLReader is based on libxml, please refer to the documentation for some functions to see if they are applicable to your libxml version.

4. DOMDocument

DOMDocument is also part of the DOM extension launched after PHP5. It can be used to create or parse html/xml. Currently, it only supports utf-8 encoding.

$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;
}

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

以上这篇php解析xml 的四种简单方法(附实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。


更多php解析xml 的四种简单方法(附实例)相关文章请关注PHP中文网!


Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools