// Create a new DomDocument $doc = new DomDocument(); // Create a new element $element = $doc->createElement('p'); // Create a text node with content "Hello, World!" $text = $doc->createTextNode('Hello, World!'); // Append the text node to the element $element->appendChild($text); // Append the element to the document $doc->appendChild($element); // Print the document echo $doc->saveHTML();
// Create a new DomDocument $doc = new DomDocument(); // Get the body element $body = $doc->getElementsByTagName('body')->item(0); // Create a new text node with content "This is a new paragraph" $text = $doc->createTextNode('This is a new paragraph.'); // Create a new paragraph element $newP = $doc->createElement('p'); // Append the text node to the new paragraph element $newP->appendChild($text); // Append the new paragraph element to the body $body->appendChild($newP); // Print the document echo $doc->saveHTML();In this example, we get the body element of an existing HTML document. We create a new text node with the content "This is a new paragraph." and a new paragraph element. We append the text node to the new paragraph element and the new paragraph element to the body. Finally, we print the document using the saveHTML() method. The createTextNode() method belongs to the PHP DomDocument package library.