我试图打开一个 api 并提取一些数据,大约 1/5 次脚本运行时会出现错误
PHP Warning: file_get_contents(http://192.168.1.52/home.cgi): failed to open stream: HTTP request failed! 1
我想在出现错误时重试打开 api,然后继续执行其余代码
这是使用 PHP5 在 Pi 上运行的
$inverterDataURL = "http://".$dataManagerIP."/home.cgi";
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$result = file_get_contents('http://192.168.1.11/home.cgi', false, $context);
运行脚本时,有 20% 的时间会在尝试打开 api 时出错,并且在没有打开 api 的情况下,我无法从中获取任何数据。 当正确打开时,脚本的其余部分运行良好
最佳答案
您应该使用循环来执行重试逻辑,该循环会在结果成功时中断。这里使用了 do ... while
循环,因为它保证它至少运行一次(因此保证 $result
将被设置为 something )。当 file_get_contents
失败时,$result
将为 false:
<?php
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
do {
$result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
if (!$result) {
echo "Waiting 3 seconds.\n";
sleep(3);
}
} while( !$result);
如果服务器出现故障,您可能会在尝试几次后需要一些东西来打破循环。该位将在 5 次失败后停止尝试。
<?php
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$attempts = 0;
do {
$attempts++;
echo "Attempt $attempts\n";
$result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
if (!$result) {
echo "Attempt $attempts has failed. Waiting 3 seconds.\n";
sleep(3);
}
} while( !$result && $attempts < 5);
关于php - 如果无法打开流,请重试 : HTTP request failed! 1 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177830/