- htmlspecialchars: documentation ( source)
- extract: documentation ( source)
<?php
class Renderer {
function render(array $_data) {
// normally you'd have some file you'd render from...
$_data = $this->escapeData($_data);
extract($_data, EXTR_SKIP);
return <<<LIST
{$foo}\n
{$bar}\n
{$baz}\n
{$htmlSafe}\n
LIST;
}
private function escapeData(array $data) {
$safe = [];
foreach ($data as $var => $value) {
if (is_array($value)) {
$safe[$var] = $this->escapeData($value);
} else {
$safe[$var] = htmlspecialchars($value);
}
}
return $safe;
}
}
class HtmlSafeString {
private $str;
function __construct($string) {
$this->str = $string;
}
function __toString() {
return $this->str;
}
}
$renderer = new Renderer();
$unsafe = [
'foo' => '<script>alert("xss");</script>',
'bar' => '<b>something</b>',
'baz' => '<i>foo</i>',
'htmlSafe' => new HtmlSafeString('<b>got through</b>')
];
echo $renderer->render($unsafe);