PHP验证XML格式是否正确

    function validxml(){
    	libxml_use_internal_errors(true); 
		$xmlstring = $_POST["xmlString"];//获取xml字符串
		$xml = new DOMDocument(); 
		$xml -> loadXML($xmlstring); //读取xml
		$xsdname='';
		if($_POST["xsdname"]!=""){//传递xsd文件名
			$xsdname=$_POST["xsdname"];
		}else{
			$xsdstring = $_POST["xsdString"];//否则读取xsd字符串
			$myfile = fopen("valid.xsd", "w") or die("Unable to open file!");//打开xsd文件
			fwrite($myfile, $xsdstring);//写入字符串
			fclose($myfile);//关闭
			$xsdname='./valid.xsd';//设置文件名
		}
		if (!$xml->schemaValidate($xsdname)) {//验证
			libxml_display_errors(); 
		} 
		else{ 
			echo "验证通过且格式良好"; 
		}
    }
    function libxml_display_errors() { 
	    $errors = libxml_get_errors(); 
	    $return="";
	    foreach ($errors as $error) { 
			$return.= "
"; switch ($error->level) { case LIBXML_ERR_WARNING: $return .= "Warning $error->code: "; break; case LIBXML_ERR_ERROR: $return .= "Error $error->code: "; break; case LIBXML_ERR_FATAL: $return .= "Fatal Error $error->code: "; break; } $return .= trim($error->message); //获取错误 if ($error->file) { $return .= " in xml file"; } $return .= " on line $error->line"; //获取错误位置 } echo $return;//返回值 libxml_clear_errors(); }

你可能感兴趣的:(PHP)