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 structure consists of tags, elements, and attributes. Tags are enclosed in angle brackets, for example
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.
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.
Use the createElement method to create new elements and set their content and attributes.
$element = $doc->createElement('element', 'Content');
$element->setAttribute('attribute', 'value');
Append child elements to parent nodes using appendChild.
$root->appendChild($element);
Remove elements from their parent using removeChild.
$parent->removeChild($element);
Directly update the content and attribute values of elements.
$element->nodeValue = 'New Content';
$element->setAttribute('attribute', 'new value');
Find matching elements by tag name using getElementsByTagName.
$elements = $doc->getElementsByTagName('element');
foreach ($elements as $element) {
// Process element
}
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.