【问题标题】:How to continue execution with in the next loop if a function throws fatal error in PHP?如果函数在 PHP 中抛出致命错误,如何在下一个循环中继续执行?
【发布时间】:2012-11-26 07:32:29
【问题描述】:

我会告诉你要点的。

我正在尝试使用 third party HTML tag stripper 抓取某些 URL,因为我认为默认的 strip_tags() 不能很好地完成这项工作。 (我认为你不需要检查那个刮板)

现在,有时,某些网站的 HTML 源代码包含一些奇怪的代码,导致我的 HTML 标签剥离器失败。

一个这样的例子是this site,它包含以下代码:

<li><a href="<//?=$cnf['website']?>girls/models-photo-gallery/?sType=6#top_menu">Photo Galleries</a></li>

导致上述标签剥离器抛出此错误:

解析错误:语法错误,意外 T_ENCAPSED_AND_WHITESPACE,期望 T_STRING 或 T_VARIABLE 或 /var/www/GET 中的 T_NUM_STRING 推文/htdocs/tmhOAuth-master/examples/class.html2text.inc(429): 第 1 行的正则表达式代码

致命错误: preg_replace() [function.preg-replace]: 评估代码失败: $this->_build_link_list("<//?=$cnf[\'website\']?>girls/models-photo-gallery/?sType=6#top_menu", /var/www/GET 中的“照片库”) Tweets/htdocs/tmhOAuth-master/examples/class.html2text.inc 上线 429

现在发生的情况是,有许多 URL 数组,其中一些会抛出上述错误。我对每个 URL 进行一些处理。

如果数组中的某个 URL 抛出这样的错误,我希望执行继续处理下一个 URL,而不会干扰任何事情。我的代码是这样的:

foreach ($results as $result)
{
    $url=$result->Url;

    $worddict2=myfunc($url,$worddict2,$history,$n_gram);        
}

这里 myfunc 进行处理并使用我之前提到的第 3 方 HTML 剥离器。 我尝试将代码修改为:

foreach ($results as $result)
    {
        $url=$result->Url;
        $worddicttemp=array();
        try
        {
            $worddicttemp=myfunc($url,$worddict2,$history,$n_gram); //returns the string represenation of what matters, hopefully
            //The below line will be executed only when the above function doesn't throw a fatal error
            $worddict2=$worddicttemp;
        }
        catch(Exception $e)
        {
            continue;
        }
    }

但我仍然遇到同样的错误。 怎么了?为什么 myfunc() 中的代码现在一遇到致命错误就将控制权转移给 catch 块?

【问题讨论】:

  • 使用 strstr 检查 $worddicttemp 中是否有错误,如果为真,则使用 continue 转到下一个 url
  • 使用 preg_replace 'e' 修饰符的 HTML 剥离器非常狂野。我会寻找其他解决方案,因为有问题的功能正在走向渡渡鸟。
  • 我相信 preg_* 的 eval 修饰符迟早会被删除,现在最好去掉。
  • 是的,它将被弃用,请参阅here
  • 在这种情况下使用它无论如何都是疯狂的。

标签: php exception-handling error-handling web-scraping fatal-error


【解决方案1】:

我建议你在解析之前使用一些美化脚本,如Tidy。你的问题可以通过添加来解决

$html_content = htmlspecialchars($html_content)

【讨论】:

    【解决方案2】:

    您无法捕获解析错误(或任何致命错误,但解析错误更糟糕,因为它们会在代码加载后立即生成)。我所知道的隔离它们的最好方法是运行完全独立的 PHP 进程来处理您想要从中恢复并期望生成致命错误的任何内容。

    另见How do I catch a PHP Fatal Error

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多