doupang1917 2010-08-26 12:40
浏览 28
已采纳

php:每当我尝试编写UTF-8时都使用DomDocument,它会写入十六进制表示法

When I try to write UTF-8 Strings into an XML file using DomDocument it actually writes the hexadecimal notation of the string instead of the string itself.

for example:

ירושלים

instead of: ירושלים

any ideas how to resolve the issue?

  • 写回答

6条回答 默认 最新

  • douji6735 2010-08-26 13:08
    关注

    Ok, here you go:

    $dom = new DOMDocument('1.0', 'utf-8');
    $dom->appendChild($dom->createElement('root'));
    $dom->documentElement->appendChild(new DOMText('ירושלים'));
    echo $dom->saveXml();
    

    will work fine, because in this case, the document you constructed will retain the encoding specified as the second argument:

    <?xml version="1.0" encoding="utf-8"?>
    <root>ירושלים</root>
    

    However, once you load XML into a Document that does not specify an encoding, you will lose anything you declared in the constructor, which means:

    $dom = new DOMDocument('1.0', 'utf-8');
    $dom->loadXml('<root/>'); // missing prolog
    $dom->documentElement->appendChild(new DOMText('ירושלים'));
    echo $dom->saveXml();
    

    will not have an encoding of utf-8:

    <?xml version="1.0"?>
    <root>&#x5D9;&#x5E8;&#x5D5;&#x5E9;&#x5DC;&#x5D9;&#x5DD;</root>
    

    So if you loadXML something, make sure it is

    $dom = new DOMDocument();
    $dom->loadXml('<?xml version="1.0" encoding="utf-8"?><root/>');
    $dom->documentElement->appendChild(new DOMText('ירושלים'));
    echo $dom->saveXml();
    

    and it will work as expected.

    As an alternative, you can also specify the encoding after loading the document.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序