Is there a why to do this? I’m new on create DomDocument. Thank you
<!DOCTYPE Data SYSTEM "http://data.data.org/schemas/data/1.234.1/data.dtd"> <Data payloadID = "123123123131231232323" timestamp = "2015-06-10T12:59:09-07:00">
$aribaXML = new DOMImplementation; $dtd = $aribaXML->createDocumentType('cXML', '', 'http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd'); $dom = $aribaXML->createDocument('', '', $dtd);
Advertisement
Answer
Here are two ways in DOM to create a new document in PHP. If you don’t need the DTD you can directly create an instance of the DOMDocument
class.
$document = new DOMDocument('1.0', "UTF-8"); $document->appendChild( $cXML = $document->createElement('cXML') ); echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?> <cXML/>
For a document with a DTD your approach was correct.
$implementation = new DOMImplementation; $dtd = $implementation->createDocumentType( 'cXML', '', 'http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd' ); $document = $implementation->createDocument("", "cXML", $dtd); $document->encoding = 'UTF-8'; $cXML = $document->documentElement; echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
After the initial bootstrap you use methods of the $document
to create nodes and append them.
// set an attribute on the document element $cXML->setAttribute('version', '1.1.007'); // xml:lang is a namespaced attribute in a reserved namespace $cXML->setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:lang', 'en-US'); // nested elements // create a node, store it for the next call and append it $cXML->appendChild( $header = $document->createElement('Header') ); $header->appendChild( $from = $document->createElement('From') ); $from->appendChild( $credential = $document->createElement('Credential') ); // "Identity" has only a text node so we don't need to store it for later $credential->appendChild( $document->createElement('Identity') )->textContent = '83528721'; // format serialized XML string $document->formatOutput = TRUE; echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd"> <cXML version="1.1.007" xml:lang="en-US"> <Header> <From> <Credential> <Identity>83528721</Identity> </Credential> </From> </Header> </cXML>