如何在简单的xml解析脚本中修复字符集


How to fix charset in simple XML-parsing script?

有一个简单的PHP脚本,用于解析XML文档并显示项目属性(属性为俄语,XML文件使用"utf-8"字符集):

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
    //header('Content-Type: text/html; charset=utf-8');
    $xml=simplexml_load_file('output.xml');
    echo $xml['moves'];
?>
</body>
</html>

我的XML:

<?xml version="1.0" encoding="UTF-8"?>
<game moves="Папа"> 
<a attr="2">123</a>
</game> 

使用此代码,我只看到"Папа"而不是"Папа"俄语文本。但是如果我删除所有的HTML并通过header() PHP方法设置charset,它将正常工作!我该怎么修理它?

当创建的文档是HTML或XHTML时,添加Doctype声明是很重要的。这也许能解决你的问题

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

如果你不确定,你应该反复检查。

首先检查XML文件是否实际上是UTF-8编码。

第二,最后检查你生成的HTML实际上是UTF-8编码的。

下面是上面的两个检查的例子:

<?php
ob_start();
?>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
    <?php
    $buffer = file_get_contents('output.xml');
    if (!preg_match('//u', $buffer)) {
        throw new Exception("XML file is not UTF-8 encoded!");
    }
    $xml = simplexml_load_string($buffer);
    echo $xml['moves'];
    ?>
    </body>
    </html>
<?php
$buffer = ob_get_clean();
if (!preg_match('//u', $buffer)) {
    throw new Exception("HTML is not UTF-8 encoded!");
}
?>