[英]How to validate xml with php
我對我的網站做了一個基於xml的api。
但有時,有些客戶向我發送了無效的xml,而我想返回一個良好的響應。
如何驗證xml?
編輯:
好的,我想我問錯了一個問題,我想驗證節點,如果缺少某些節點,則返回最佳響應。
我曾經用php來驗證這一點,我必須檢查每個節點。 但是這種方式很難修改。
這是我的xml示例:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mashhadhost>
<create>
<name>example.ir</name>
<period>60</period>
<ns>
<hostAttr>
<hostName>ns1.example.ir</hostName>
<hostAddr ip="v4">192.0.2.2</hostAddr>
</hostAttr>
</ns>
<contact type="holder">ex61-irnic</contact>
<contact type="admin">ex61-irnic</contact>
<contact type="tech">ex61-irnic</contact>
<contact type="bill">ex61-irnic</contact>
</create>
<auth>
<code>TOKEN</code>
</auth>
</mashhadhost>
不幸的是,在我的案例中,XMLReader沒有驗證很多事情。
這是我前一段時間寫的一小節課:
/**
* Class XmlValidator
* @author Francesco Casula <fra.casula@gmail.com>
*/
class XmlValidator
{
/**
* @param string $xmlFilename Path to the XML file
* @param string $version 1.0
* @param string $encoding utf-8
* @return bool
*/
public function isXMLFileValid($xmlFilename, $version = '1.0', $encoding = 'utf-8')
{
$xmlContent = file_get_contents($xmlFilename);
return $this->isXMLContentValid($xmlContent, $version, $encoding);
}
/**
* @param string $xmlContent A well-formed XML string
* @param string $version 1.0
* @param string $encoding utf-8
* @return bool
*/
public function isXMLContentValid($xmlContent, $version = '1.0', $encoding = 'utf-8')
{
if (trim($xmlContent) == '') {
return false;
}
libxml_use_internal_errors(true);
$doc = new DOMDocument($version, $encoding);
$doc->loadXML($xmlContent);
$errors = libxml_get_errors();
libxml_clear_errors();
return empty($errors);
}
}
它也可以與流和vfsStream一起很好地用於測試目的。
如果您只想檢查文檔的格式是否正確(您不在乎DTD的有效性,甚至沒有DTD進行驗證),請使用Domdocument而不是XMLReader來驗證文件,因為XMLReader將流您在文檔中不立即加載它,因此isValid()方法將僅檢查第一個節點。 您可以嘗試這樣的代碼:
$doc = new \DOMDocument();
if(@$doc->load($filePath)){
var_dump("$filePath is a valid XML document");
} else {
var_dump("$filePath is NOT a valid document");
}
您可以使用XMLReader::isValid()
。
<?php
$xml = XMLReader::open('xmlfile.xml');
// You must to use it
$xml->setParserProperty(XMLReader::VALIDATE, true);
var_dump($xml->isValid());
?>
PHP文檔正是您所需要的!
我確定您已經定義了正確的DTD,對嗎?
<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
echo "This document is valid!\n";
}
?>
您可以使用PHP函數:-
$xmlcontents = XMLReader::open('filename.xml');
$xmlcontents->setParserProperty(XMLReader::VALIDATE, true);
var_dump($xmlcontents->isValid());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.