PHP DOMDocument - 如何强制使用数字字符引用或实体,而不是 UTF8


PHP DOMDocument - How to force using numeric character references or entities, not UTF8

我有一个DOMDocument,我正在附加一些节点。在某些文本内容中,有特殊字符,如©、–、δ等...

我的目标是在DOMDocument中插入这些字符时,它们将分别转换为数字字符引用 (NCR) 或实体:

© - ©
– - –
δ - δ

将编码设置为不包含这些字符的字符集,例如 us-ascii

例:

$dom = new DOMDocument();
$dom->loadXML('<foo>©</foo>');
$dom->encoding = 'us-ascii';
print($dom->saveXML());

导致:

<?xml version="1.0" encoding="us-ascii"?>
<foo>&#169;</foo>

要将实体更改为十六进制,您可以应用类似

preg_replace('/&#([0-9]+);/e', '''&#x''.strtoupper(dechex($1)).'';''', $xml);

到 XML 输出。