Validate XML using a custom DTD in PHP

前端 未结 4 1298
温柔的废话
温柔的废话 2021-01-02 03:37

Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?

4条回答
  •  难免孤独
    2021-01-02 04:34

    If you have the dtd in a string, you can validate against it by using a data wrapper for the dtd:

    $xml = '
            
            
                Tove
                Jani
                Reminder
                Don\'t forget me this weekend!
            ';
    
    $dtd = '
            
            
            
            ';
    
    
    $root = 'note';
    
    $systemId = 'data://text/plain;base64,'.base64_encode($dtd);
    
    $old = new DOMDocument;
    $old->loadXML($xml);
    
    $creator = new DOMImplementation;
    $doctype = $creator->createDocumentType($root, null, $systemId);
    $new = $creator->createDocument(null, null, $doctype);
    $new->encoding = "utf-8";
    
    $oldNode = $old->getElementsByTagName($root)->item(0);
    $newNode = $new->importNode($oldNode, true);
    $new->appendChild($newNode);
    
    if (@$new->validate()) {
        echo "Valid";
    } else {
        echo "Not valid";
    }
    

提交回复
热议问题