Current Location: Home> Latest Articles> Comprehensive PHP XML Tutorial: Creating, Parsing, and Common Operations

Comprehensive PHP XML Tutorial: Creating, Parsing, and Common Operations

gitbox 2025-08-05

Introduction

XML (Extensible Markup Language) is a universal format used to describe and transfer data. PHP, as a widely used server-side language, offers rich functionality to handle XML, facilitating data exchange and storage between applications.

XML Basics

XML Syntax

XML structure consists of tags, elements, and attributes. Tags are enclosed in angle brackets, for example . Elements are formed by start and end tags, like content. Attributes provide additional information about elements, such as content. XML also supports comments and document type declarations.

Creating XML Documents

In PHP, you can create XML documents using the DOM extension. By instantiating a DOMDocument object and using its methods, you can add elements and attributes to build a complete XML file.


$doc = new DOMDocument('1.0', 'UTF-8');
$root = $doc->createElement('root');
$element = $doc->createElement('element', 'Hello World');
$element->setAttribute('attribute', 'value');
$root->appendChild($element);
$doc->appendChild($root);
$doc->formatOutput = true;
$doc->save('output.xml');

The above code demonstrates how to create a simple XML document and save it as a file.

Parsing XML Documents

You can also use DOMDocument to load existing XML files or strings and iterate through nodes and attributes.


$doc = new DOMDocument();
$doc->load('input.xml');
$root = $doc->documentElement;
$elements = $root->getElementsByTagName('element');
foreach ($elements as $element) {
    $content = $element->nodeValue;
    $attribute = $element->getAttribute('attribute');
    echo "Content: $content, Attribute: $attribute \n";
}

This code snippet loops through elements in the XML and outputs their content and attributes.

Common XML Operations

Creating Elements

Use the createElement method to create new elements and set their content and attributes.


$element = $doc->createElement('element', 'Content');
$element->setAttribute('attribute', 'value');

Adding Elements

Append child elements to parent nodes using appendChild.


$root->appendChild($element);

Deleting Elements

Remove elements from their parent using removeChild.


$parent->removeChild($element);

Modifying Elements

Directly update the content and attribute values of elements.


$element->nodeValue = 'New Content';
$element->setAttribute('attribute', 'new value');

Querying Elements

Find matching elements by tag name using getElementsByTagName.


$elements = $doc->getElementsByTagName('element');
foreach ($elements as $element) {
    // Process element
}

Conclusion

This article systematically introduced the core methods for manipulating XML with PHP, covering creation, parsing, and common element operations. With these skills, you can efficiently handle XML data and implement diverse application scenarios.