如何在 PHP 中不显示警告的情况下检查字符串是否是有效的 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4554233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:26:24  来源:igfitidea点击:

How check if a String is a Valid XML with-out Displaying a Warning in PHP

xmlsimplexmlphplibxml2

提问by jspeshu

i was trying to check the validity of a string as xml using this simplexml_load_string()Docsfunction but it displays a lot of warning messages.

我试图使用此simplexml_load_string()Docs函数检查字符串作为 xml 的有效性, 但它显示了很多警告消息。

How can I check whether a string is a valid XML without suppressing (@at the beginning) the error anddisplaying a warning function that expec

如何@不抑制(在开头)错误显示期望的警告函数的情况下检查字符串是否是有效的 XML

回答by Tjirp

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

使用 libxml_use_internal_errors() 抑制所有 XML 错误,然后使用 libxml_get_errors() 迭代它们。

Simple XML loading string

简单的 XML 加载字符串

libxml_use_internal_errors(true);

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

回答by Felix Kling

From the documentation:

文档

Dealing with XML errors when loading documents is a very simple task. Using the libxmlfunctionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLErrorobject, returned by libxml_get_errors(), contains several properties including the message, lineand column(position) of the error.

在加载文档时处理 XML 错误是一项非常简单的任务。使用该libxml功能可以在加载文档时抑制所有 XML 错误,然后迭代这些错误。

libXMLError由 返回的对象libxml_get_errors()包含多个属性,包括错误的messagelinecolumn(位置)。

libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (!$sxe) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}

Reference: libxml_use_internal_errors

参考: libxml_use_internal_errors

回答by Jkhaled

try this one

试试这个

//check if xml is valid document
public function _isValidXML($xml) {
    $doc = @simplexml_load_string($xml);
    if ($doc) {
        return true; //this is valid
    } else {
        return false; //this is not valid
    }
}

回答by admin

My version like this:

我的版本是这样的:

//validate only XML. HTML will be ignored.

function isValidXml($content)
{
    $content = trim($content);
    if (empty($content)) {
        return false;
    }
    //html go to hell!
    if (stripos($content, '<!DOCTYPE html>') !== false) {
        return false;
    }

    libxml_use_internal_errors(true);
    simplexml_load_string($content);
    $errors = libxml_get_errors();          
    libxml_clear_errors();  

    return empty($errors);
}

Tests:

测试:

//false
var_dump(isValidXml('<!DOCTYPE html><html><body></body></html>'));
//true
var_dump(isValidXml('<?xml version="1.0" standalone="yes"?><root></root>'));
//false
var_dump(isValidXml(null));
//false
var_dump(isValidXml(1));
//false
var_dump(isValidXml(false));
//false
var_dump(isValidXml('asdasds'));

回答by Francesco Casula

Here a small piece of class I wrote a while ago:

这是我前段时间写的一小段类:

/**
 * Class XmlParser
 * @author Francesco Casula <[email protected]>
 */
class XmlParser
{
    /**
     * @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);
    }
}

It works fine with streams and vfsStreamas well for testing purposes.

它适用于流和vfsStream以及用于测试目的。

回答by aexl

Case

案件

Occasionally check availability of a Google Merchant XML feed.

偶尔检查 Google Merchant XML Feed 的可用性。

The feed is without DTD, so validate()won't work.

提要没有 DTD,所以validate()不会工作。

Solution

解决方案

// disable forwarding those load() errors to PHP
libxml_use_internal_errors(true);
// initiate the DOMDocument and attempt to load the XML file
$dom = new \DOMDocument;
$dom->load($path_to_xml_file);
// check if the file contents are what we're expecting them to be
// `item` here is for Google Merchant, replace with what you expect
$success = $dom->getElementsByTagName('item')->length > 0;
// alternatively, just check if the file was loaded successfully
$success = null !== $dom->actualEncoding;

lengthabove contains a number of how many products are actually listed in the file. You can use your tag names instead.

length上面包含了文件中实际列出的产品数量。您可以改用您的标签名称。

Logic

逻辑

You can call getElementsByTagName()on any other tag names (itemI used is for Google Merchant, your case may vary), or read other propertieson the $domobject itself. The logic stays the same: instead of checking if there were errors when loading the file, I believe actually trying to manipulate it (or specifically check if it contains the values you actually need) would be more reliable.

您可以拨打getElementsByTagName()任何其他标记名称(item我用的是谷歌为商人,你的情况可能会有所不同),或者阅读其它性能上的$dom对象本身。逻辑保持不变:我相信实际上尝试操作它(或专门检查它是否包含您实际需要的值)会更可靠,而不是在加载文件时检查是否有错误。

Most important: unlike validate(), this won't require your XML to have a DTD.

最重要的是:与 不同validate(),这不需要您的 XML 具有 DTD。