Hi,
I'm using PHP5's DOM API (http://www.php.net/manual/en/ref.dom.php) to build a XHTML 1.1 page. I can successfully create a DOMDocument object, but how do I modify the DOCTYPE of the DOMDocument object? Please note that the DOMDocument::doctype property is read-only.

In a nutshell, I'd like to build one very simple XHTML 1.1 compliant web page (not a whole site) using just the DOM API.

    Using a regular expression on the XML string works:

    $docType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
    
    $xmlString = preg_replace('/(\<\?xml.+?>)(?!<!DOCTYPE)/s', "\\1\r\n{$docType}\r\n", $xmlString);
    

    I would be interested to know if there is a more elegant why.

    Infact, there is 😉. If you have the Tidy extension avialable to you or the option of compiling and/or enabling it, you can get that to do all the work for you. I use this on one of my sites to tidy up use submitted HTML and turn it into XHTML.

      i would like to know a more elegant way as well, if it exists

        I figured it out. Here's some code showcasing how to do it:

        <?php
        	header('Cache-Control: no-cache, must-revalidate'); // HTTP/1.1
        	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        	//if(!headers_sent()) exit('no headers were sent');
        
        $doctype = DOMImplementation::createDocumentType('html',
        							'-//W3C//DTD XHTML 1.1//EN',
        							'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd');
        $dom = DOMImplementation::createDocument(null, null, $doctype);
        $dom->encoding = 'UTF-8';
        $dom->formatOutput = true;
        $dom->resolveExternals = false;
        
        $html = $dom->appendChild(new DOMElement('html'));
        $head = $html->appendChild(new DOMElement('head'));
        $title = $head->appendChild(new DOMElement('title', 'page title'));
        $body = $html->appendChild(new DOMElement('body'));
        $div = $body->appendChild(new DOMElement('div', 'some text'));
        
        // Output the XML
        echo $dom->saveXML();
        ?>
          Write a Reply...