2012-07-30 60 views
1

我一直在努力解决如何在PHP中验证XSD与XSD的关系,但是由于缺少示例而未能这样做。我读过is_Valid()XMLReader中的XML验证()

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

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

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

感谢

回答

0

首先,使用DOM。它更强大,将读者和作者融为一体 - 我认为没有理由不这样做。它也有更多的逻辑接口(恕我直言)。

一旦你这样做,DOMDocument::schemaValidate()做你以后。

+0

我无法使用DOM,因为我的XML文件很大,DOM无法处理。 – BentCoder 2012-07-30 11:50:19

+1

@DaveRandom DOM功能强大,但该功能需要花费。这两种工具都有完全不同的用例,并且以各自的方式强大。与XMLReader相比,dom非常昂贵。 DOM会将整个文档加载到内存中。 XMLReader使您能够更高效地读取文档,并且可以在需要时将单个节点加载到dom中。您将能够获得更好的性能并节省(可能性很大)的资源。对于处理较小XML文件的应用程序也是如此。 “正确的”选择取决于要求。两者都不是“更好”。 – 2015-05-28 00:30:21

0

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

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

+0

我用'set_error_handler('validation_error_handler',E_WARNING);'和手动处理错误,工作正常。 – BentCoder 2013-06-18 13:28:58

0

我创建了性能基准测试: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个字节

DOM文档 - 483.04295539856毫秒,369280个字节

所以我决定去与DOM文档,只是用自己的XML和XSD尝试并使用你的更快的选择。