How to load XML when PHP can't indicate the right encoding?

前端 未结 4 1608
梦谈多话
梦谈多话 2020-12-12 00:08

I\'m trying to load an XML source from a remote location, so i have no control of the formatting. Unfortunately the XML file I\'m trying to load has no encoding:

<         


        
4条回答
  •  伪装坚强ぢ
    2020-12-12 00:52

    You've to convert your document into UTF-8, the easiest would be to use utf8_encode().

    DOMdocument example:

    $doc = new DOMDocument();
    $content = utf8_encode(file_get_contents($url));
    $doc->loadXML($content);
    

    SimpleXML example:

    $xmlInput = simplexml_load_string(utf8_encode(file_get_contents($url_or_file)));
    

    If you don't know the current encoding, use mb_detect_encoding(), for example:

    $content = utf8_encode(file_get_contents($url_or_file));
    $encoding = mb_detect_encoding($content);
    $doc = new DOMdocument();
    $res = $doc->loadXML("" . $content);
    

    Notes:

    • If encoding cannot be detected (function will return FALSE), you may try to force the encoding via utf8_encode().
    • If you're loading html code via $doc->loadHTML instead, you can still use XML header.

    If you know the encoding, use iconv() to convert it:

    $xml = iconv('ISO-8859-1' ,'UTF-8', $xmlInput)
    

提交回复
热议问题