根据用户输入,我创建了一个基于XML的文档。其中一个XML节点包含一个CDATA节。如果在CDATA节中插入的字符是“特殊”的(我认为是控制字符),那么整个XML将变得无效。
例如:
$dom = new DOMDocument('1.0', 'utf-8');
$dom->appendChild($dom->createElement('root'))
->appendChild($dom->createCDATASection(
"This is some text with a SOH char \x01."
));
$test = new DOMDocument;
$test->loadXml($dom->saveXML());
echo $test->saveXml();
将会给予
Warning: DOMDocument::loadXML(): CData section not finished
This is some text with a SOH cha in Entity, line: 2 in /newfile.php on line 17
Warning: DOMDocument::loadXML(): PCDATA invalid Char value 1 in Entity, line: 2 in /newfile.php on line 17
Warning: DOMDocument::loadXML(): Sequence ']]>' not allowed in content in Entity, line: 2 in /newfile.php on line 17
Warning: DOMDocument::loadXML(): Sequence ']]>' not allowed in content in Entity, line: 2 in /newfile.php on line 17
Warning: DOMDocument::loadXML(): internal errorExtra content at the end of the document in Entity, line: 2 in /newfile.php on line 17
<?xml version="1.0"?>
有没有一种好的方法在PHP中确保CDATA部分是有效的?
filter_var([], FILTER_SANITIZE_STRING)
开始。 - GajusDOMDocument
没有采取措施来保证XML输出。包含]]>
或控制字符的CDATA不会被检查,包含--
的注释节点也不会被检查。即使使用DOMDocument
,这两种情况都是创建无效XML的简单方法。 - Francis Avila