I wrote a function :
function wrapWithTag($tag, $data) {
$cdata = "<![CDATA[$data]]>";
echo "<$tag>$cdata</$tag>";
}
For instance I like to use it as
$name = 'myCellContent - <extra>';
wrapWithTag("td", $name);
The expected output would be a html table cell with string:
myCellContent - <extra>
What it actually does is printing empty cells. How can I use CDATA properly?
Edit: I have got a simple workaround:
function wrapWithTag($tag, $data) {
$data = str_replace("<", "<", $data);
echo "<$tag>$data</$tag>";
}
However, I would prefer using a CDATA section. Feel free to post a solution :P
CDATA sections are a feature of XML. HTML does not support them.
XHTML does, but you must ensure the browser is parsing the document in XML mode (by setting Content-Type: application/xhtml+xml
in the HTTP response headers).
In HTML, if you want to use characters which have special meaning, you must use entities such as <
.
PHP has the htmlspecialchars
function; there's no need to roll your own with str_replace
.