file_get_contents()或cURL来处理40 *和50 *错误以及200个响应代码

时间:2018-03-18 19:01:46

标签: php curl file-get-contents

我使用file_get_contents()启动了我的PHP脚本,我正在使用在线数据库,我可以使用URL从中获取JSON,但有时(我无法帮助)我回来了40 *或50 *错误响应代码,我想知道你们是否可以告诉我在cURL和file_get_contents之间使用什么更好,因为基本上每次我都要检查响应代码并在其上切换案例以确定我做什么下。

  • 200 =>获取文件
  • 403 =>打印“错误”
  • 502 =>打印'坏网关'
  • ...

希望我很清楚,先谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用cURL获取响应标头并解析HTTP status

 Select dropdown = new SelectElement(driver.findelement(By.id("dropdown")));
 dropdown.selectByVisibleText("Germany"); or dropdown.selectByIndex(2);

可能的输出:

$ch = curl_init('example.com');
curl_setopt($ch, CURLOPT_HEADER, true); // get the header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // get the data (body)
$ret = curl_exec($ch);
curl_close($ch);

// split header/body according to HTTP protocol
list($header, $body) = explode("\r\n\r\n", $ret);
// split header lines
$header_lines = explode("\r\n", $header) ;
// get the first line, ex: "HTTP/1.1 301 Moved Permanently"
$status_line = array_shift($header_lines);
// split elements : Protocol / Code / Message
$status_items = explode(' ', $status_line, 3);

print_r($status_items);

然后,您可以使用Array ( [0] => HTTP/1.1 [1] => 301 [2] => Moved Permanently ) 检查所请求页面的状态。并使用包含您的JSON的$status_items[1]

另见: