How to chain like element with php domdocument?

by wilmer.lemke , in category: PHP General , 7 months ago

How to chain like element with php domdocument?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 7 months ago

@wilmer.lemke 

To chain elements with PHP DOMDocument, you can follow these steps:

  1. Create a new instance of the DOMDocument class.
1
$dom = new DOMDocument();


  1. Create the root element using the createElement() method.
1
$root = $dom->createElement('root');


  1. 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);


  1. 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'));


  1. Append the root element to the DOMDocument.
1
$dom->appendChild($root);


  1. 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.