2012-09-20 59 views
4

是否可以使用存儲在字符串中的XSD shema驗證SimpleXMLElement?使用XSD進行PHP SimpleXMLElement驗證

我得到這個XML低谷捲曲:

<production_feedback> 
     <production_number>DA1100208</production_number> 
    <production_status>DONE</production_status> 
</production_feedback> 

在我身邊我得到這樣的:

if ($_SERVER['REQUEST_METHOD'] === 'POST'){ 

    $post_text = file_get_contents('php://input'); 

    $xml = new SimpleXMLElement($post_text); 

    error_log(print_r($xml , true)); 
    } 

這是我error_log()

SimpleXMLElement Object\n(\n [production_number] => DA1100208\n [production_status] => PRODUCTION_IN_PROGRESS\n)\n 

,所以我可以用Xpath訪問數據。這很好。我想用XSD驗證它。是否有可能,或者有沒有其他方法2用XSD字符串驗證XML字符串?

這是我的XSD BTW存儲在一個變量:

$production_XSD ='<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="production_feedback"> 
    <xs:complexType> 
     <xs:sequence> 
     <xs:element type="xs:string" name="production_number"/> 
     <xs:element type="xs:string" name="production_status"/> 
     </xs:sequence> 
    </xs:complexType> 
    </xs:element> 
</xs:schema>' 

回答

5

爲SimpleXMLElement類不支持(只要在php.net的文檔是最新的)。

DOMDocument提供了使用DOMDocument :: schemaValidateSource方法查找的功能。

----原

然而,XMLReader類具有可用於驗證對一個XSD 文件中的setSchema方法(這不正是你要找的,但是這是我的發現,而無需依賴對任何外部庫)

+0

我必須將字符串保存到xml文件才能使用xml讀取器或? –

+0

是的,我認爲是。 (你可以直接寫下這個文件,然後再刪除它,但我不知道你是否想這樣做) 當使用RelaxNG Schema時,你可以直接將模式字符串傳遞給setRelaxNGSchemaSource方法(但是,不知道放鬆NG,所以我不能告訴你這是否是一種好的方法)。 –

+0

我剛剛找到[DOMDocument](http://php.net/manual/de/class.domdocument.php)類,它支持使用DOMDocument :: schemaValidateSource方法根據模式字符串驗證XML。你可能想嘗試一下。 –

0

我最近需要驗證包含對XSD文件的XML字符串變種,因此,如果其他人正在尋找這種解決方案,請參閱以下內容:

// $xml_feed is a string containing your XML content 
// validate xml string with xsd file 
$doc = new DOMDocument(); 
$doc->loadXML($xml_feed); // load xml 
$is_valid_xml = $doc->schemaValidate('XSDs/FeedFile.xsd'); // path to xsd file 

if (!$is_valid_xml){ 
    echo '<b>Invalid XML:</b> validation failed<br>'; 
}else{ 
    echo '<b>Valid XML:</b> validation passed<br>'; 
} 

如果你還有你的XSD存儲在一個字符串中,那麼用包含你的XSD的var替換'XSDs/FeedFile.xsd'..希望有人認爲這有幫助!