How to chain like element with php domdocument?

by wilmer.lemke , in category: PHP General , a year ago

How to chain like element with php domdocument?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , a year 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.

Related Threads:

How to use the Composite design pattern in PHP for tree-like structures?
How to use the Chain of Responsibility design pattern in PHP for handling requests?
How to search for an element in an array in PHP?
How to parse html element using php?
How to check if element is in a nested array php??
How to access form element in while loop in php?