問題: UTF8 で「完全にエンコードされた」XML ファイルが必要です。つまり、シンボルを表すエンティティがなく、すべてのシンボルが UTF8 でエンコードされています。ただし、XML で予約されている「&」(amp)、「<」(lt)、および「">」(gt) の 3 つのみを除きます。そして、エンティティを実際の UTF8 文字に (XML を破壊することなく) 変換するため
に、それを高速に行う組み込み関数が必要です。
PS: これは「現実世界の問題」です (!)。たとえば、PMC/journals には、特別な XML DTD (JATS 形式とも呼ばれます) でエンコードされた 280 万の科学記事があります... 「通常のXML-UTF8-テキスト」として処理するには、数値エンティティから UTF8 に変更する必要があります。文字。
試行された解決策: このタスクの自然な関数はhtml_entity_decodeですが、XML コード (!) を破棄し、予約済みの 3 つの XML 予約済みシンボルを変換します。
問題の説明
仮定する
$xmlFrag ='<p>Hello world!    Let A<B and A=∬dxdy</p>';
エンティティ 160 (nbsp) および x222C (二重積分) は UTF8 に変換する必要があり、XML 予約は変換しlt
ないでください。XML テキストは (変換後)、
$xmlFrag = '<p>
こんにちは! A <
B とし、A=∬dxdy </p>
';
テキスト「A<B」には XML 予約文字が必要なため、そのままにしておく必要がありますA<B
。
欲求不満の解決策
私は問題を(直接!)解決するために使用しようとしています...そのため、オプションhtml_entity_decode
を使用するためにPHPをv5.5に更新しました。ENT_XML1
$s = html_entity_decode($xmlFrag, ENT_XML1, 'UTF-8'); // not working
// as I expected
おそらく別の質問は、「私が期待したことを行うための他のオプションがないのはなぜですか?」ということです。-- これは、私だけでなく、他の多くの XML アプリケーション (!) にとって重要です。
答えとして回避策は必要ありません... OK、醜い関数を示します。問題を理解するのに役立つかもしれません。
function xml_entity_decode($s) {
// here an illustration (by user-defined function)
// about how the hypothetical PHP-build-in-function MUST work
static $XENTITIES = array('&','>','<');
static $XSAFENTITIES = array('#_x_amp#;','#_x_gt#;','#_x_lt#;');
$s = str_replace($XENTITIES,$XSAFENTITIES,$s);
//$s = html_entity_decode($s, ENT_NOQUOTES, 'UTF-8'); // any php version
$s = html_entity_decode($s, ENT_HTML5|ENT_NOQUOTES, 'UTF-8'); // PHP 5.3+
$s = str_replace($XSAFENTITIES,$XENTITIES,$s);
return $s;
} // you see? not need a benchmark:
// it is not so fast as direct use of html_entity_decode; if there
// was an XML-safe option was ideal.
PS:この回答後に修正されました。本当にすべての名前付きエンティティENT_HTML5
を変換するには、フラグである必要があります。