PHP simplexml_load_file - 捕获文件错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1917876/
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 04:17:49  来源:igfitidea点击:

PHP simplexml_load_file - catch file errors

phpxmlsimplexml

提问by yoda

Is it possible to catch simplexml file errors? I'm connecting to a webservice that sometimes fails, and I need to make the system skip a file if it returns some http error or something similar.

是否可以捕获 simplexml 文件错误?我正在连接到一个有时会失败的网络服务,如果它返回一些 http 错误或类似的东西,我需要让系统跳过一个文件。

回答by Mārti?? Briedis

Using @is just plain dirty.

使用@只是简单的脏。

If you look at the manual, there is an options parameter:

如果您查看手册,则有一个 options 参数:

SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

All option list is available here: http://www.php.net/manual/en/libxml.constants.php

所有选项列表都可以在这里找到:http: //www.php.net/manual/en/libxml.constants.php

This is the correct way to suppress warnings:

这是抑制警告的正确方法:

$xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);

回答by zombat

You're talking about two different things. HTTP errors will have nothing to do with whether an XML file is valid, so you're looking at two separate areas of error handling.

你说的是两件不同的事情。HTTP 错误与 XML 文件是否有效无关,因此您正在查看错误处理的两个不同领域。

You can take advantage of libxml_use_internal_errors()to suppress any XML parsing errors, and then check for them manually (using libxml_get_errors()) after each parse operation. I'd suggest doing it this way, as your scripts won't produce a ton of E_WARNINGmessages, but you'll still find the invalid XML files.

您可以利用libxml_use_internal_errors()来抑制任何 XML 解析错误,然后在每次解析操作后手动检查它们(使用libxml_get_errors())。我建议这样做,因为您的脚本不会产生大量E_WARNING消息,但您仍然会找到无效的 XML 文件。

As for HTTP errors, handling those will depend on how you're connecting to the webservice and retrieving the data.

至于 HTTP 错误,处理这些错误取决于您如何连接到 Web 服务并检索数据。

回答by Andy Baird

On error, your simplexml_load_file should return false.

出错时,您的 simplexml_load_file 应返回 false。

So doing somethign as simple as this:

所以做一些像这样简单的事情:

   $xml = @simplexml_load_file('myfile');
   if (!$xml) {
      echo "Uh oh's, we have an error!";
   }

Is one way to detect errors.

是一种检测错误的方法。

回答by leepowers

If you're not interested in error reporting or logging when the webservice fails you can use the error supression operator:

如果您对 Web 服务失败时的错误报告或日志记录不感兴趣,您可以使用错误抑制运算符:

$xml= @simplexml_load_file('http://tri.ad/test.xml');
if ($xml) {
 // Do some stuff . . .
}

But this is a simple hack. A more robust solution would be to load the XML file with cURL, log any failed requests, parse any XML document returned with simplexml_load_string, log any XML parse errors and then do some stuff with the valid XML.

但这是一个简单的黑客。更强大的解决方案是使用cURL加载 XML 文件,记录任何失败的请求,解析使用 返回的任何 XML 文档simplexml_load_string,记录任何 XML 解析错误,然后使用有效的 XML 执行一些操作。

回答by kojow7

Another option is to use the libxml_use_internal_errors()function to capture the errors. The errors can then be retrieved using the libxml_get_errors()function. This will allow you to loop through them if you want to check what the specific errors are. If you do use this method, you will want to make sure that you clear the errors from memory when you are done with them so they are not wasting your memory space.

另一种选择是使用该libxml_use_internal_errors()函数来捕获错误。然后可以使用该libxml_get_errors()函数检索错误。如果您想检查特定错误是什么,这将允许您遍历它们。如果您确实使用此方法,您需要确保在完成错误后清除内存中的错误,以免它们浪费您的内存空间。

Here is an example:

下面是一个例子:

<?php
    //Store errors in memory rather than outputting them
    libxml_use_internal_errors(true);

    $xml = simplexml_load_file('myfile.xml');

    if (!$xml){
        //Exit because we can't process a broken file
        exit;
    }

    //Important to clear the error buffer
    libxml_clear_errors();

    //Display your xml code
    print_r($xml);

Another example actually making use of the errors we captured:

另一个实际利用我们捕获的错误的示例:

<?php
    //Store errors in memory rather than outputting them
    libxml_use_internal_errors(true);

    $xml = simplexml_load_file('myfile.xml');

    if (!$xml){

        echo "Your script is not valid due to the following errors:\n";

        //Process error messages
        foreach(libxml_get_errors() as $error){
           echo "$error";
        }

        //Exit because we can't process a broken file
        exit;
    }

    //Important to clear the error buffer
    libxml_clear_errors();

    //Display your xml code
    print_r($xml);

回答by Dominic Barnes

You can set up an error handler within PHP to throw an Exception upon any PHP Errors: (Example and further documentation found here: PHP.net)

您可以在 PHP 中设置一个错误处理程序,以在任何 PHP 错误时抛出异常:(在此处找到示例和更多文档:PHP.net

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

回答by k...

if (!$xml=simplexml_load_file('./samplexml.xml')) {  
    trigger_error('Error reading XML file',E_USER_ERROR);
}

foreach ($xml as $syn) {
    $candelete = $syn->candelete;
    $forpayroll = $syn->forpayroll;
    $name = $syn->name;
    $sql = "INSERT INTO vtiger (candelete, forpayroll, name) VALUES('$candelete','$forpayroll','$name')";
    $query = mysql_query($sql);
}