php-检测错误请求

php-检测错误请求,php,arrays,json,request,Php,Arrays,Json,Request,我有2个JSON源,其中一个回复400个错误请求(取决于服务器的收费) 因此,我希望我的php代码检查两个服务器的答案,并选择一个工作 <?php $server1 = 'server1.lan' $server2 = 'server2.lan' /* Here a code to check and select the working server */ $json=file_get_contents('https://'.$workingServer.'/v1/data?sour

我有2个JSON源,其中一个回复400个错误请求(取决于服务器的收费) 因此,我希望我的php代码检查两个服务器的答案,并选择一个工作

<?php
$server1 = 'server1.lan'
$server2 = 'server2.lan'

/*
Here a code to check and select the working server
*/

$json=file_get_contents('https://'.$workingServer.'/v1/data?source='.$_GET['source']);
$data =  json_decode($json);
if (count($data->data)) {

        // Cycle through the array
        foreach ($data->data as $idx => $data) {
echo "<p>$data->name</p>\n";
?>


谢谢

在调用
file\u get\u contents
后,检查
$http\u response\u header

$json = file_get_contents(('https://'.$server1.'/v1/data?source='.$_GET['source']);

if (strpos($http_response_header[0],"400") > 0)
{
  $json = file_get_contents(('https://'.$server.'/v1/data?source='.$_GET['source']);
}

下面的示例介绍了您可能想要实现的功能。您的目标是获得这种想法,并以您自己的方式实现类似的内容,使用正常的错误处理和消除代码重复:

$json = file_get_contents('https://server1.lan/v1/data');
if ($json === false) 
{
    $json = file_get_contents('https://server2.lan/v1/data');
    if ($json === false) 
    {
        die('Both servers are unavailable');
    }
}
失败时返回布尔值
false
,因此如果第一台服务器不可用,请调用第二台服务器。如果它也不可用,请退出脚本,或者执行某种您喜欢的错误处理

您可能希望创建一个可能的服务器名称数组,并使用一个函数对所有这些名称进行迭代,直到找到一个工作名称,然后返回内容,或者在失败时抛出异常

我还建议您使用,它为您提供了查看请求错误代码、自定义请求本身等选项