口音和ñxml问题

时间:2014-12-17 02:08:49

标签: php xml parsing

我正在尝试创建一个文档XML,但我遇到了一些问题。我需要替换口音和字母ñ。

以下代码的输出:

header('Content-type: text/html; charset=utf-8'); 
var_dump($this->xml_entities_s("Relucí"));

It shows:
string 'Reducí'

当我尝试创建XML时:

header('Content-type: text/xml; charset=utf-8');
$output = '<?xml version="1.0" encoding="UTF-8"?>';
$output .= $this->xml_entities_s("Relucí");
echo $output;


It shows:
string 'Reducí' 
And I want this to show:
string 'Reduc&#237;'

我需要显示上述内容,因为有一个站点从我的站点获取数据,并且他们要求使用&#237;在xml中以这种方式获取数据,以便可以正确解析它。

    private function xml_entities_s($string) {
           return str_replace(array("<",">",'"',"'","&","á","Á","é","É","í","Í","ó","Ó","ú","Ú","ñ","Ñ"),
                       array("&lt;","&gt;","&quot;","&apos;","&amp;","&#225;","&#193;","&#233;","&#201;","&#237;","&#205;","&#243;","&#211;","&#250;","&#218;","&#241;","&#209;"),
                       $string);
    }
你能帮忙解决这个问题吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

你真的不需要编码字符。 UTF-8支持它们。只需要编码具有特殊含义的字符(如<)。如果您正在使用DOM来生成XML,它将负责处理它。

如果要生成ASCII XML,可以在构造函数中定义:

$dom = new DOMDocument('1.0', 'ASCII');
$dom
  ->appendChild($dom->createElement('div'))
  ->appendChild($dom->createTextNode('Relucí'));

echo $dom->saveXml();

输出:

<?xml version="1.0" encoding="ASCII"?>
<div>Reluc&#237;</div>