Parsing and Generating XML Files in PHP
This article explains how to use PHP's built-in XML extension to parse XML files into a DOM tree and to generate XML documents programmatically, providing step‑by‑step code examples for loading, traversing, creating elements, setting attributes, and saving the resulting XML files.
XML (eXtensible Markup Language) is a widely used markup language for data storage and exchange. PHP provides a built‑in XML extension that allows developers to parse and generate XML files easily.
Parsing XML files: PHP's XML parser can read an XML file or string and convert it into an internal DOM tree, making data manipulation straightforward.
<?php // 创建DOM对象 $dom = new DOMDocument(); // 加载XML文件 $dom->load('data.xml'); // 获取根元素 $root = $dom->documentElement; // 遍历子节点 foreach ($root->childNodes as $node) { // 判断是否为元素节点 if ($node->nodeType == XML_ELEMENT_NODE) { // 获取节点的标签名和文本内容 $tag = $node->tagName; $text = $node->textContent; echo "标签名: $tag, 内容: $text"; } } ?>
The example creates a DOMDocument object, loads data.xml , obtains the root element, and iterates over its child nodes. For each element node, it retrieves the tag name and text content and prints them.
Generating XML files: Besides parsing, PHP can also create XML documents by constructing elements and attributes, then saving the DOM to a file.
<?php // 创建DOM对象和根元素 $dom = new DOMDocument(); $root = $dom->createElement('root'); $dom->appendChild($root); // 创建子元素和属性 $element = $dom->createElement('element'); $element->setAttribute('attribute', 'value'); $root->appendChild($element); // 将DOM对象保存为XML文件 $dom->save('output.xml'); ?>
This code creates a new DOM document, adds a root element named root , then creates a child element element with an attribute attribute="value" . Finally, it saves the structure to output.xml .
Notes: Ensure the XML file being parsed is well‑formed; otherwise parsing will fail. The described functions provide a convenient way to handle XML data in PHP, useful for configuration, data exchange, and storage tasks.
Summary: The article demonstrates how to parse XML into a DOM tree and how to generate XML documents using PHP's XML extension, offering practical code snippets that are valuable for backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.