简体   繁体   English

PHP libxml中针对XSD的XML验证

[英]XML Validation against XSD in PHP libxml

I have created an xml like below 我创建了一个像下面的xml

<Request>
    <RequestType>Logon</RequestType>
    <MobileId>23424</MobileId>
    <Password>123456Gg</Password>
</Request>

and my xsd file is like below code 我的xsd文件就像下面的代码

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Request" type="RequestType"/>
<xsd:complexType name="RequestType">
    <xsd:sequence>
        <xsd:element name="RequestType">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:enumeration value="Logon"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
        <xsd:element name="MobileId" >
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:minLength value="0" />
                    <xsd:maxLength value="10" />
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
        <xsd:element name="Password">
            <xsd:simpleType>
                <xsd:restriction base="xsd:string">
                    <xsd:minLength value="0"/>
                    <xsd:maxLength value="255"/>
                </xsd:restriction>
            </xsd:simpleType>
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>
</xsd:schema>

I have used PHP'S DOMDocument's schemaValidate function to validate the xml against the xsd, and it gives following error 我使用PHP'S DOMDocument的schemaValidate函数来验证xml对xsd,并给出以下错误

Fatal Error 4: Start tag expected, '<' not found on line 5 
Error 1872: The document has no document element. on line 0

But I have tested those two files (xml and xsd) in this link W3C XML Schema Online validation , and it successfully validates without showing any error. 但是我在这个链接W3C XML Schema Online验证中测试了这两个文件(xml和xsd),并且它成功验证而没有显示任何错误。

What I have to do to get work this in php? 我需要做什么才能在php中完成这项工作?

Note: my php libxml version is 2.7.8 注意:我的php libxml版本是2.7.8

dom specially gives two functions to validate with schema. dom特别提供了两个函数来验证模式。 One is to give file path 一个是给文件路径

$doc = new DOMDocument();
$doc->load('PATH TO XML');

$is_valid_xml = $doc->schemaValidate('PATH TO XSD');

or else you could use 或者你可以使用

$is_valid_xml = $doc->schemaValidateSource($source)

This source should be a string containing the schema. 此源应该是包含架构的字符串。 It seems that you are using schemaValidateSource function other than schemaValidate. 您似乎使用schemaValidate以外的schemaValidateSource函数。 (Once I was stuck in the same place) cheers (一旦我被困在同一个地方)欢呼

Just close your xsd file: 只需关闭您的xsd文件:

</xsd:schema>

I try it now, and for me this works. 我现在试试,对我来说这很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM