代码之家  ›  专栏  ›  技术社区  ›  Olivier Lalonde Danny

使用DOMDocument进行PHP编码

  •  22
  • Olivier Lalonde Danny  · 技术社区  · 16 年前
    <tag>
    Алекс М
    </tag>
    

    当我尝试使用domdocument函数获取以下代码的内容时,它返回如下内容:

    ÐÐ»ÐµÐºÑ Ðœ
    

    我尝试将domdocument编码设置为不同的值(utf-8、iso-8859-1),使用mb_convert_编码、iconv和utf8_编码,但没有成功。

    我怎样才能得到“______”而不是“____

    编辑:输入来自加载了curl的页面。当我将页面内容输出到浏览器时,字符会正确显示(因此我怀疑输入是否有问题)。

    3 回复  |  直到 14 年前
        1
  •  42
  •   Dmytro Zavalkin    16 年前

    尝试:

    $string = file_get_contents('your-xml-file.xml');
    $string = mb_convert_encoding($string, 'utf-8', mb_detect_encoding($string));
    // if you have not escaped entities use
    $string = mb_convert_encoding($string, 'html-entities', 'utf-8'); 
    $doc = new DOMDocument();
    $doc->loadXML($string);
    
        2
  •  19
  •   Nemke    14 年前

    在使用xpath解析domdocument之后,我遇到了类似的问题

    https://bugs.php.net/bug.php?id=32547

    我是这样解决的

    // Workaround because PHP 5.2.x has encoding problems, when we 
    // update to PHP 5.3 this line is not necesserry any more
    $content = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' . $content;
    
    // Creating new DOM document and loading HTML content
    $dom_document = new DOMDocument('1.0', 'UTF-8');
    $dom_document->substituteEntities = TRUE;
    $dom_document->loadHTML($content);
    
        3
  •  6
  •   Ilia Kondrashov    15 年前

    向标记添加XML头-尝试此操作:

    $a = new DOMDocument ();
    $a->loadXml ('<?xml version="1.0" encoding="UTF-8"?><tag>Алекс М</tag>');
    print htmlspecialchars ($a->saveXml ());
    
    推荐文章