Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: min(nine, four)?
(Example: nine)

The Note You're Voting On

mikek dot nospam at nospam dot muonics dot com
18 years ago
With regard to the note below about needing htmlentities to avoid warnings about unterminated entity references, I thought it worthwhile to mention that that you don't need to with createTextNode and DOMText::__construct. If you mix both methods of setting text nodes and do (or don't) apply htmlentities consistently to all data to be displayed, you'll get &s (or warnings and badly-formed xml).

It's probably in one's best interest to extend DOMElement and DOMDocument so that it creates a DOMText node and appends it, rather than passing it up to the DOMElement constructor. Otherwise, good luck using (or not using) htmlentities in all the right places in your code, especially as code changes get made.

<?php

class XDOMElement extends DOMElement {
function
__construct($name, $value = null, $namespaceURI = null) {
parent::__construct($name, null, $namespaceURI);
}
}

class
XDOMDocument extends DOMDocument {
function
__construct($version = null, $encoding = null) {
parent::__construct($version, $encoding);
$this->registerNodeClass('DOMElement', 'XDOMElement');
}

function
createElement($name, $value = null, $namespaceURI = null) {
$element = new XDOMElement($name, $value, $namespaceURI);
$element = $this->importNode($element);
if (!empty(
$value)) {
$element->appendChild(new DOMText($value));
}
return
$element;
}
}

$doc1 = new XDOMDocument();
$doc1_e1 = $doc1->createElement('foo', 'bar & baz');
$doc1->appendChild($doc1_e1);
echo
$doc1->saveXML();

$doc2 = new XDOMDocument();
$doc2_e1 = $doc2->createElement('foo');
$doc2->appendChild($doc2_e1);
$doc2_e1->appendChild($doc2->createTextNode('bar & baz'));
echo
$doc2->saveXML();

?>

Text specified in createElement:
<?xml version=""?>
<foo>bar &amp; baz</foo>

Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>

<< Back to user notes page

To Top