PHP XML 教程:创建、解析、读取示例

⚡ 智能摘要

PHP and XML work together to structure, store, and exchange data between systems. This walkthrough explains XML, the DOM, and XML parsers, then shows how to read an XML document with SimpleXML and how to create one with the DOMDocument class, ending with when to use each.

  • 📄 什么是 XML: XML is Extensible Markup Language, a tag-based format that lets you define custom tags to structure and transport data.
  • 🌳 The DOM: The Document Object Model views an XML or HTML document as a tree, so code can navigate and edit nodes.
  • 🔄 XML Parsers: A parser converts an XML document into a DOM object that PHP, Java脚本,或 Python can read and change.
  • ???? Reading XML: simplexml_load_file loads a file into objects, so you access records with arrow syntax like $xml->record->name.
  • 🛠️ Creating XML: The DOMDocument class builds a document node by node with createElement and appendChild, then save writes the file.
  • SimpleXML vs DOM: SimpleXML is quick for reading, while DOMDocument suits precise creation and complex manipulation.
  • 🤖 人工智能辅助: AI tools can generate parsing code for a specific XML structure and convert between XML, JSON, and PHP arrays.

PHP and XML

什么是 XML?

XML 是可扩展标记语言的缩写。

XML is used to structure, store, and transport data from one system to another.

XML is similar to HTML. It uses opening and closing tags. Unlike HTML, XML allows users to define their own tags.

什么是DOM?

DOM 是文档对象模型的缩写。

It is a cross-platform and language-neutral standard that defines how to access and manipulate data in:

  • HTML
  • 的XHTML
  • XML

DOM XML 用于访问和操作 XML 文档。它 查看 XML 文档 as a tree structure.

XML 解析器

An XML parser is a program that translates the XML document into an XML Document Object Model (DOM) object.

The XML DOM object can then be manipulated using Java脚本, Python, PHP, and other languages.

The keyword CDATA, which is the acronym for (unparsed) Character Data, is used to ignore special characters such as “<” and “>” when parsing an XML document.

为什么使用 XML?

  • Web services such as SOAP and REST use the XML format to exchange information. Learning what XML is and how it works gives you a competitive advantage as a developer, since modern applications make heavy use of web services.
  • XML documents can be used to store the configuration settings of an application.
  • It allows you to create your own custom tags, which makes it more flexible.

XML 文档示例

Let us suppose that you are developing 一个从 Web 服务以 XML 格式获取数据的应用程序。

Below is a sample of what the XML document looks like.

<?xml version="1.0" encoding="utf-8"?>
<employees status = "ok">
<record man_no = "101">
<name>Joe Paul</name>
<position>CEO</position>
</record>
<record man_no = "102">
<name>Tasha Smith</name>
<position>Finance Manager</position>
</record>
</employees>

这里,

  • “<?xml version=”1.0″ encoding=”utf-8″?>” specifies the XML version and encoding to be used
  • “ ” 是根元素。
  • “<record…>…</record>” are the child elements, one per employee record.

如何使用 PHP 读取 XML

Let us now write the code that will read the employees XML document and display the results in a web browser. 的index.php

<?php
$xml = simplexml_load_file('employees.xml');
echo '<h2>Employees Listing</h2>';
$list = $xml->record;
for ($i = 0; $i < count($list); $i++) {
echo '<b>Man no:</b> ' . $list[$i]->attributes()->man_no . '<br>';
echo 'Name: ' . $list[$i]->name . '<br>';
echo 'Position: ' . $list[$i]->position . '<br><br>';
}
?>

这里,

  • “$xml = simplexml_load_file(’employees.xml’);” uses the simplexml_load_file function to load the file named employees.xml and assign the contents to the variable $xml.
  • “$list = $xml->record;” gets the contents of the record nodes.
  • “for ($i = 0; $i < count(…)…” is the for loop that reads the array and outputs the results
  • “$list[$i]->attributes()->man_no;”读取元素的man_no属性
  • “$list[$i]->name;”读取name子元素的值
  • “$list[$i]->position;”读取position子元素的值

Testing the XML Reader

Assuming you saved the file index.php in the phptuts/xml folder, browse to the URL http://localhost/phptuts/xml/index.php

使用 PHP 读取 XML

如何使用 PHP 创建 XML 文档

我们现在将研究如何使用 PHP 创建 XML 文档。

The following code uses the PHP built-in class DOMDocument to create an XML document.

<?php

$dom = new DOMDocument();

$dom->encoding = 'utf-8';

$dom->xmlVersion = '1.0';

$dom->formatOutput = true;

$xml_file_name = 'movies_list.xml';

$root = $dom->createElement('Movies');

$movie_node = $dom->createElement('movie');

$attr_movie_id = new DOMAttr('movie_id', '5467');

$movie_node->setAttributeNode($attr_movie_id);

$child_node_title = $dom->createElement('Title', 'The Campaign');

$movie_node->appendChild($child_node_title);

$child_node_year = $dom->createElement('Year', 2012);

$movie_node->appendChild($child_node_year);

$child_node_genre = $dom->createElement('Genre', 'Comedy');

$movie_node->appendChild($child_node_genre);

$child_node_ratings = $dom->createElement('Ratings', 6.2);

$movie_node->appendChild($child_node_ratings);

$root->appendChild($movie_node);

$dom->appendChild($root);

$dom->save($xml_file_name);

echo "$xml_file_name has been successfully created";
?>

这里,

  • “$dom = new DOMDocument();” creates an instance of the DOMDocument class.
  • “$dom->encoding = 'utf-8';”将文档编码设置为 utf-8
  • “$dom->xmlVersion = '1.0';”指定版本号1.0
  • “$dom->formatOutput = true;” 确保输出格式正确
  • “$root = $dom->createElement('Movies');” 创建名为 Movies 的根节点
  • “$attr_movie_id = new DOMAttr(‘movie_id’, ‘5467’);” defines the movie_id attribute of the movie node
  • “$dom->createElement(‘ElementName’, ‘ElementValue’)” creates a child node. ElementName specifies the name of the element, e.g. Title. ElementValue sets the child node value, e.g. The Campaign.
  • “$root->appendChild($movie_node);” appends the movie node to the root node Movies
  • “$dom->appendChild($root);”将根节点附加到 XML 文档。
  • “$dom->save($xml_file_name);”将XML文件保存在Web服务器的根目录中。
  • “echo “$xml_file_name has been successfully created”;” displays a success message.

Testing the XML Creator

Assuming you saved the file create_movies_list.php in the phptuts/xml folder, browse to the URL http://localhost/phptuts/xml/create_movies_list.php

使用 PHP 创建 XML 文档

Open the movies_list.xml file.

使用 PHP 创建 XML 文档

SimpleXML vs DOMDocument

PHP offers two main ways to work with XML. SimpleXML is best when you mainly need to read data, while DOMDocument gives finer control for building and heavily editing documents. The table below compares them.

方面 SimpleXML的 DOM文档
使用方便 Very simple; the document behaves like nested objects More verbose, node-based API
最适合 Reading and light editing Creating documents and complex manipulation
访问样式 $xml->record->name createElement() and appendChild()
XPath 支持 Yes, via ->xpath() Yes, via the DOMXPath class

A practical rule is to reach for SimpleXML first for reading feeds and simple files, and switch to DOMDocument when you need to create documents, insert nodes at specific positions, or validate against a schema.

常见问题

Both store structured data, but XML uses tags and supports attributes, comments, and schemas, while JSON is lighter and maps directly to arrays and objects. JSON is common for APIs; XML suits documents and configuration.

Load the file with SimpleXML or DOMDocument, change the node values or attributes, then write it back. With SimpleXML, edit the property and call asXML(‘file.xml’); with DOMDocument, edit the node and call save().

XPath is a query language for selecting nodes in an XML document. In PHP, call $xml->xpath(‘//record/name’) with SimpleXML, or use the DOMXPath class, to fetch matching elements without looping through the whole tree.

Yes. AI can generate code using simplexml_load_string, json_encode, and json_decode to convert between the formats, and flag data that does not map cleanly, such as XML attributes or mixed content. Verify the result.

Yes. Paste a sample of your XML, and AI can produce SimpleXML or DOMDocument code that reads the exact elements and attributes you need, including loops for repeated records. Test it against real files.

总结一下这篇文章: