[英]Loop the PHP Code Until Statement Is True
我正在使用兩個API密鑰來接收數據。 這是因為提供程序有一些每日配額限制。 如果配額超過每日限制,服務器將返回403錯誤。
我使用$ http_response_header檢查服務器的響應。 但是問題在於,當返回的響應不是200時,例如,所使用的API密鑰超過了每日限制,則代碼應再次執行,以便隨機選擇另一個API密鑰。 這是我正在使用的代碼:
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else{
echo 'No';
}
您可以創建此代碼的函數,然后在響應不為200時重新運行該函數。也許是這樣?
function getAPIData() {
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else {
getAPIData();
}
}
就像@Jaquarh所說,您可能還想更改max_execution_time。 在這里看看,看看有什么適合您的。
請嘗試這個
$data = null;
do {
$keys = array('1stkey','2ndkey')
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
} while ($data == null);
我已經創建了完美的解決方案,請檢查以下內容:
$api = array('1st key','2nd key');
$k = array_rand($api);
$api_key_yt = $api[$k];
$total_api=count($api);
for ($loop=0;$loop<=$total_api;$loop++) {
$api_key_yt=$api[$loop];
$request2 = "https://example.com/?data&key=$api_key_yt";
$response = file_get_contents($request2);
$jsonobj = json_decode($response);
if (isset($jsonobj->items)) {break;} else {unset($jsonobj);}
}
print_r($jsonobj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.