PHP simplexml_load_file - 捕获文件错误

时间:2022-03-06 00:12:09

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文件错误?我正在连接到有时会失败的web服务,如果它返回一些http错误或类似的东西,我需要让系统跳过一个文件。

7 个解决方案

#1


8  

Using @ is just plain dirty.

使用@只是简单的脏。

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

如果查看手册,则有一个选项参数:

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);

#2


6  

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_WARNING messages, 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服务并检索数据。

#3


6  

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文件,记录任何失败的请求,解析使用simplexml_load_string返回的任何XML文档,记录任何XML解析错误,然后使用有效的XML执行一些操作。

#4


5  

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.

是一种检测错误的方法。

#5


2  

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");

#6


1  

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);

#7


0  

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);
}

#1


8  

Using @ is just plain dirty.

使用@只是简单的脏。

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

如果查看手册,则有一个选项参数:

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);

#2


6  

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_WARNING messages, 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服务并检索数据。

#3


6  

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文件,记录任何失败的请求,解析使用simplexml_load_string返回的任何XML文档,记录任何XML解析错误,然后使用有效的XML执行一些操作。

#4


5  

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.

是一种检测错误的方法。

#5


2  

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");

#6


1  

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);

#7


0  

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);
}