gpt4 book ai didi

php - 如何用php验证xml

转载 作者:可可西里 更新时间:2023-10-31 23:08:04 25 4
gpt4 key购买 nike

我已经为我的网站制作了一个带有基于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com