@wilmer.lemke
To chain elements with PHP DOMDocument, you can follow these steps:
- Create a new instance of the DOMDocument class.
1
|
$dom = new DOMDocument();
|
- Create the root element using the createElement() method.
1
|
$root = $dom->createElement('root');
|
- Create child elements using the createElement() method and append them to the root element.
1
2
3
4
5
|
$child1 = $dom->createElement('child1');
$root->appendChild($child1);
$child2 = $dom->createElement('child2');
$root->appendChild($child2);
|
- Chain methods to add attributes, text, or other elements to the child elements.
1
2
3
4
5
6
7
|
$child1->setAttribute('attr1', 'value1')
->setAttribute('attr2', 'value2')
->appendChild($dom->createTextNode('Text for child1'));
$child2->setAttribute('attr3', 'value3')
->setAttribute('attr4', 'value4')
->appendChild($dom->createTextNode('Text for child2'));
|
- Append the root element to the DOMDocument.
1
|
$dom->appendChild($root);
|
- Save the DOMDocument to a file or output it as a string.
1
2
3
4
|
$dom->save('output.xml'); // Save to file
// Output as string
echo $dom->saveXML();
|
This way, you can chain element creation, attribute setting, and text appending in a fluent manner using the PHP DOMDocument API.