使用XSD进行PHP SimpleXMLElement验证

Bar*_*más 5 php xml validation xsd

是否可以使用存储在字符串中的XSD shema验证SimpleXMLElement?

我得到这个xml槽CURL:

<production_feedback>
        <production_number>DA1100208</production_number>
    <production_status>DONE</production_status>
</production_feedback>
Run Code Online (Sandbox Code Playgroud)

在我这边我得到这样的:

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

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

    $xml = new SimpleXMLElement($post_text);

    error_log(print_r($xml , true));
    }
Run Code Online (Sandbox Code Playgroud)

这是我的error_log():

SimpleXMLElement Object\n(\n    [production_number] => DA1100208\n    [production_status] => PRODUCTION_IN_PROGRESS\n)\n
Run Code Online (Sandbox Code Playgroud)

所以我可以使用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>'
Run Code Online (Sandbox Code Playgroud)

Lou*_*uer 5

SimpleXMLElement类不支持(就php.net上的文档是最新的).

DOM文档提供你正在寻找使用DOMDocument :: schemaValidateSource方法的功能.

- - 原版的

然而,XMLReader类有setSchema方法,可用于对XSD 文件进行验证(这不是你想要的,但这是我发现的而不依赖于任何外部库)