Validating PHP SimpleXMLElement with XSD

Is it possible to check a SimpleXMLElement element with an XSD shema stored in a string?

I get this xml crough curl:

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

On my side, I get the following:

 if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){ $post_text = file_get_contents('php://input'); $xml = new SimpleXMLElement($post_text); error_log(print_r($xml , true)); } 

This is in my error_log() :

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

So, I can access the data using Xpath. It works well. I would like to test it using XSD. Is this possible, or is there another way 2 to check the XML string using the XSD string?

this is my XSD bit stored in a variable:

 $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>' 
+4
source share
2 answers

The SimpleXMLElement class does not support this (how relevant is the documentation on php.net).

DOMDocument provides the functionality you are looking for using the DOMDocument :: schemaValidateSource method.

---- Original

The XMLReader class however has a setSchema method that can be used to check for an XSD file (This is not quite what you were looking for, but what I found without relying on any external libraries)

+5
source

I recently needed to check a varistor containing an XML string for an XSD file, so if anyone else is looking for this solution, see below:

 // $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>'; } 

If you also saved your XSD in a line, replace "XSDs / FeedFile.xsd" with var containing your XSD .. hope someone finds this useful!

0
source

Source: https://habr.com/ru/post/1435204/


All Articles