php - 如何用php验证xml

标签 php xml xml-validation

我已经为我的网站制作了一个带有基于 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以及用于测试目的。

关于php - 如何用php验证xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17191866/

相关文章:

c++ - Qt XML验证错误处理

xml - xsd :choice? 的 minOccurs 和 maxOccurs 的含义

java - 向 JAX-B 生成的元素添加静态属性

php - SQL子查询从不同的表获取信息

php - MYSQL比较同一列中的值

并发数据库调用的 PHP/Mysql 问题

java - XML:直接获取 XML 元素

android - 如何在电子商务应用程序中将 ListView 项目显示为项目?

c# - 使用 DTD 验证 - 强制关闭连接

php - katerina 字体的数字