【问题标题】:XML validation in XMLReader()XMLReader() 中的 XML 验证
【发布时间】:2012-07-27 23:11:51
【问题描述】:

我一直在尝试研究如何在 PHP 中针对 XSD 验证 XML,但由于缺乏示例而未能这样做。我读过 is_Valid() 等。

我想出了下面的例子,但它不能正常工作。

$reader = new XMLReader();
$reader->open('items.xml');
$reader->setSchema('items.xsd');

//Now how do validate against XSD and print errors here

谢谢

【问题讨论】:

    标签: php xml xsd xmlreader


    【解决方案1】:

    我创建了一个性能基准:XMLReader vs DOMDocument

    XMLReader.php:

        $script_starttime = microtime(true);
        libxml_use_internal_errors(true);
    
        $xml = new XMLReader; 
        $xml->open($_FILES["file"]["tmp_name"]); 
        $xml->setSchema($xmlschema);        
    
        while (@$xml->read()) {};
    
        if (count(libxml_get_errors ())==0) {
            echo 'good';            
        } else {
            echo 'error';
        }
    
        echo '<br><br>Time: ',(microtime(true) - $script_starttime)*1000," ms, Memory: ".memory_get_usage()." bytes";
    

    DOMDocument.php:

        $script_starttime = microtime(true);
        libxml_use_internal_errors(true);
    
        $xml = new DOMDocument(); 
        $xmlfile = $_FILES["file"]["tmp_name"];
        $xml->load($xmlfile); 
    
        if ($xml->schemaValidate($xmlschema)) {
            echo 'good';        
        } else {
            echo 'error';
        }
    
        echo '<br><br>Time: ',(microtime(true) - $script_starttime)*1000," ms, Memory: ".memory_get_usage()." bytes";
    

    我的示例:18 MB xml,258.230 行

    结果:

    XMLReader - 656.14199638367 毫秒,379064 字节

    DOMDocument - 483.04295539856 毫秒,369280 字节

    所以我决定使用 DOMDocument,但只需尝试使用您自己的 xml 和 xsd 并使用您更快的选择。

    【讨论】:

      【解决方案2】:

      我刚刚在这里创建了关于验证的类似答案: Getting PHP's XMLReader to not throw php errors in invalid documents

      但最重要的是,如果不传递整个文档,您将无法使用 XMLReader 进行验证。这种情况类似于数据库结果集 - 您必须通过文档节点迭代(XMLReader 的读取方法),并且每个节点仅在您读取它时才被验证(有时甚至更晚)

      【讨论】:

      • 我使用了set_error_handler('validation_error_handler', E_WARNING); 并手动处理了错误,效果很好。
      【解决方案3】:

      首先,使用DOM。它更强大,将读者和作家合二为一——我认为没有理由不这样做。它还有一个更合乎逻辑的界面(恕我直言)。

      一旦你这样做了,DOMDocument::schemaValidate() 就会做你想做的事。

      【讨论】:

      • 我不能使用 DOM,因为我的 XML 文件很大,DOM 无法处理。
      • @DaveRandom DOM 很强大,但这种力量是有代价的。这两种工具都有完全不同的用例,并且以自己的方式强大。与 XMLReader 相比,dom 非常昂贵。 DOM 会将整个文档加载到内存中。 XMLReader 使您能够更有效地读取文档,并且您可以在需要时将单个节点加载到 dom 中。您将能够获得更好的性能并节省(可能很多)资源。对于处理较小 XML 文件的应用程序也是如此。 “正确”的选择取决于要求。两者都不是“更好”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 2014-02-10
      相关资源
      最近更新 更多