针对PHP libxml中的XSD的XML验证 [英] XML Validation against XSD in PHP libxml

查看:90
本文介绍了针对PHP libxml中的XSD的XML验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了如下所示的xml

I have created an xml like below

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

我的xsd文件就像下面的代码

and my xsd file is like below code

<?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>

我已经使用PHP的DOMDocument的schemaValidate函数针对xsd验证了xml,并给出了以下错误消息

I have used PHP'S DOMDocument's schemaValidate function to validate the xml against the xsd, and it gives following error

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

但是我已经在此链接中测试了这两个文件(xml和xsd) W3C XML架构在线验证,它可以成功验证而不会显示任何错误.

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.

我需要做什么才能在php中工作?

What I have to do to get work this in php?

注意:我的php libxml版本是2.7.8

Note: my php libxml version is 2.7.8

推荐答案

dom专门提供了两个用于验证架构的函数. 一种是提供文件路径

dom specially gives two functions to validate with schema. One is to give file path

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

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

否则您可以使用

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

此源应为包含架构的字符串. 似乎您使用的不是schemaValidate,而是使用schemaValidateSource函数. (一旦我被困在同一个地方) 欢呼

This source should be a string containing the schema. It seems that you are using schemaValidateSource function other than schemaValidate. (Once I was stuck in the same place) cheers

这篇关于针对PHP libxml中的XSD的XML验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆