How do I tell DOMDocument->load() what encoding I want it to use?

前端 未结 3 1254
旧巷少年郎
旧巷少年郎 2021-01-04 10:48

I search for and process XML files from elsewhere, and need to transform them with some XSLTs. No problem. Using PHP5 and the DOM library, everything\'s a snap. Worked fine,

3条回答
  •  -上瘾入骨i
    2021-01-04 11:16

    I haven't found a way to set the default encoding (yet) but maybe the recover mode is feasible in this case.
    When libxml encounters an encoding error and no encoding has been explicitly set it switches from unicode/utf8 to latin1 and continues parsing the document. But in the parser context the property wellFormed is set to 0/false. PHP's DOM extension considers the document valid if wellFormed is true or the DOMDocument object's attribute recover is true.

    '.chr(0xE4).'';
    
    $doc = new DOMDocument;
    $b = $doc->loadxml($xml);
    echo 'with doc->recover=false(default) : ', ($b) ? 'success':'failed', "\n";
    
    $doc = new DOMDocument;
    $doc->recover = true;
    $b = $doc->loadxml($xml);
    echo 'with doc->recover=true : ', ($b) ? 'success':'failed', "\n";
    

    prints

    Warning: DOMDocument::loadXML(): Input is not proper UTF-8, indicate encoding !
    Bytes: 0xE4 0x3C 0x2F 0x66 in Entity, line: 1 in test.php on line 6
    with doc->recover=false(default) : failed
    
    Warning: DOMDocument::loadXML(): Input is not proper UTF-8, indicate encoding !
    Bytes: 0xE4 0x3C 0x2F 0x66 in Entity, line: 1 in  test.php on line 11
    with doc->recover=true : success
    

    You still get the warning message (which can be suppressed with @$doc->load()) and it will also show up in the internal libxml errors (only once when the parser switches from utf8 to latin1). The error code for this particular error will be 9 (XML_ERR_INVALID_CHAR).

    
        %s
        %s
        &
    ', chr(0xE4),chr(0xF6));
    
    libxml_use_internal_errors(true);
    $doc = new DOMDocument;
    $doc->recover = true;
    libxml_clear_errors();
    $b = $doc->loadxml($xml);
    $invalidCharFound = false;
    foreach(libxml_get_errors() as $error) {
        if ( 9==$error->code && !$invalidCharFound ) {
            $invalidCharFound = true;
            echo "found invalid char, possibly harmless\n";
        }
        else {
            echo "hm, that's probably more severe: ", $error->message, "\n";
        }
    }
    

提交回复
热议问题