【问题标题】:How to validate DOMDocument object [duplicate]如何验证 DOMDocument 对象 [重复]
【发布时间】:2013-03-29 12:34:53
【问题描述】:
$rss = new DOMDocument();
$rss->load($url);

如果我希望用户提供任何 rssfeed 链接以获取 xml 文档,并且用户试图提供任何不包含任何 xml 文档的随机链接。它肯定会显示错误或警告。

如何验证这种情况?

【问题讨论】:

    标签: php xml dom


    【解决方案1】:

    使用libxml_use_internal_errors 自行处理错误。来自http://php.net/manual/de/function.libxml-use-internal-errors.php的示例

    // enable user error handling
    libxml_use_internal_errors(true);
    
    // load the document
    $doc = new DOMDocument;
    
    if (!$doc->load('file.xml')) {
        foreach (libxml_get_errors() as $error) {
            // handle errors here
        }
    
        libxml_clear_errors();
    }
    

    【讨论】:

    • 非常感谢redreggae。你节省了我的时间。它奏效了。
    【解决方案2】:

    您可以使用 load 的返回值来检查错误并使用@ 抑制输出

    $rss = new DOMDocument();
    if (@$rss->load($url) == false) {
        //error...
    }
    

    【讨论】:

    • 即使现在它显示警告“警告:DOMDocument::load() [domdocument.load]: EntityRef: expecting”。
    • 您是否使用 set_error_handler 设置了自己的错误处理程序?
    【解决方案3】:

    试试这个:

    $errors = array();
    set_error_handler(function ($number, $error) use (&$errors) {
        if (preg_match('#^DOMDocument::load\(\):#', $error)) {
            $errors[] = $error;
        }
    });
    
    $url = '';
    $doc = new DOMDocument();
    if ($doc->load($url) === false) {
        // handle errors from $errors
    }
    
    restore_error_handler();
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2018-12-05
      • 2015-09-30
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2021-10-05
      相关资源
      最近更新 更多