XML Validation against XSD in PHP libxml

Kanagu picture Kanagu · Jan 6, 2014 · Viewed 11.3k times · Source

I have created an xml like below

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

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>

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

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.

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

Note: my php libxml version is 2.7.8

Answer

User123456 picture User123456 · Mar 27, 2014

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');

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. (Once I was stuck in the same place) cheers