dongye9820 2009-08-13 19:46
浏览 71
已采纳

针对PHP中给定DTD的XML验证

In PHP, I am trying to validate an XML document using a DTD specified by my application - not by the externally fetched XML document. The validate method in the DOMDocument class seems to only validate using the DTD specified by the XML document itself, so this will not work.

Can this be done, and how, or do I have to translate my DTD to an XML schema so I can use the schemaValidate method?

(this seems to have been asked in Validate XML using a custom DTD in PHP but without correct answer, since the solution only relies on DTD speicified by the target XML)

  • 写回答

2条回答 默认 最新

  • dsc56927 2009-08-13 22:08
    关注

    Note: XML validation could be subject to the Billion Laughs attack, and similar DoS vectors.

    This essentially does what rojoca mentioned in his comment:

    <?php
    
    $xml = <<<END
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE foo SYSTEM "foo.dtd">
    <foo>
        <bar>baz</bar>
    </foo>
    END;
    
    $root = 'foo';
    
    $old = new DOMDocument;
    $old->loadXML($xml);
    
    $creator = new DOMImplementation;
    $doctype = $creator->createDocumentType($root, null, 'bar.dtd');
    $new = $creator->createDocument(null, null, $doctype);
    $new->encoding = "utf-8";
    
    $oldNode = $old->getElementsByTagName($root)->item(0);
    $newNode = $new->importNode($oldNode, true);
    $new->appendChild($newNode);
    
    $new->validate();
    
    ?>
    

    This will validate the document against the bar.dtd.

    You can't just call $new->loadXML(), because that would just set the DTD to the original, and the doctype property of a DOMDocument object is read-only, so you have to copy the root node (with everything in it) to a new DOM document.

    I only just had a go with this myself, so I'm not entirely sure if this covers everything, but it definitely works for the XML in my example.

    Of course, the quick-and-dirty solution would be to first get the XML as a string, search and replace the original DTD by your own DTD and then load it.

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

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像