/ php

Load XML and validate with XSD

This following example it loads and do the validation of a XML file against the specified XSD file.
XSD files are "XML Schemas" that describe the structure of a XML document.
Some lines were added to report errors, but they are optional, but recomended.

function load_and validate_xml($filename_xml, $filename_xsd)
{
    libxml_use_internal_errors(true);
    $product_schema_errors=array();
    
    $xml_doc = new DOMDocument();
    $xml_doc->load($filename_xml);
    $valid_xml = $xml_doc->schemaValidate($filename_xsd) ? $xml_doc : false;

    foreach (libxml_get_errors() as $error) {
        $product_schema_errors[]=$error; // handle errors
    }
    libxml_clear_errors();

    // if valid xml, save it to array
    if($valid_xml){
        $valid_xml_array = xml_to_array($filename_xml);
        tracking_log('', basename($filename_xml), '', 'OK', 'SCHEMA VALIDATION', '');
    }else{
        $msg=json_encode($product_schema_errors);
        fn_nl_digitecgalaxus_log('', basename($filename_xml), $msg, 'ERROR', 'SCHEMA VALIDATION', '');
    }

    return !empty($valid_xml_array) ? $valid_xml_array : FALSE;
}
Load XML and validate with XSD
Share this

Subscribe to NL Slack