相关疑难解决方法(0)

使用file_get_contents的HTTP请求,获取响应代码

我正在尝试file_get_contentsstream_context_createPOST 一起使用.我的代码到目前为止:

    $options = array('http' => array(
        'method'  => 'POST',
        'content' => $data,
        'header'  => 
            "Content-Type: text/plain\r\n" .
            "Content-Length: " . strlen($data) . "\r\n"
    ));
    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是,当发生HTTP错误时,它会发出警告:

file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
Run Code Online (Sandbox Code Playgroud)

并返回false.有办法:

  • 抑制警告(我打算在失败的情况下抛出自己的异常)
  • 从流中获取错误信息(至少是响应代码)

php http file stream

76
推荐指数
3
解决办法
7万
查看次数

使用file_get_contents进行良好的错误处理

我正在使用simplehtmldom,它有这个功能:

// get html dom form file
function file_get_html() {
    $dom = new simple_html_dom;
    $args = func_get_args();
    $dom->load(call_user_func_array('file_get_contents', $args), true);
    return $dom;
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

$html3 = file_get_html(urlencode(trim("$link")));
Run Code Online (Sandbox Code Playgroud)

有时,URL可能无效,我想处理这个问题.我以为我可以使用try和catch但是这没有用,因为它没有抛出异常,它只是给出一个像这样的php警告:

[06-Aug-2010 19:59:42] PHP Warning:  file_get_contents(http://new.mysite.com/ghs 1/) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found  in /home/example/public_html/other/simple_html_dom.php on line 39
Run Code Online (Sandbox Code Playgroud)

第39行在上面的代码中.

我怎样才能正确处理这个错误,我可以只使用普通if条件,它看起来不像是返回一个布尔值.

谢谢大家的帮助

更新

这是一个好的解决方案吗?

if(fopen(urlencode(trim("$next_url")), 'r')){

    $html3 = file_get_html(urlencode(trim("$next_url")));

}else{
    //do other stuff, error_logging
    return false;

}
Run Code Online (Sandbox Code Playgroud)

php error-handling

18
推荐指数
1
解决办法
3万
查看次数

标签 统计

php ×2

error-handling ×1

file ×1

http ×1

stream ×1