[英]How to get json api that doesnt read every time the best way
I have this function in php which tries to read a json api and it can take up to 10 attempts to read it and I want to send that response to view, but the function takes to long to run and will often not work, how can I make the code run better我在 php 中有这个函数,它试图读取一个 json api,它可能需要多达 10 次尝试来读取它,我想将该响应发送给视图,但是该函数需要很长时间才能运行并且通常不起作用,怎么办我让代码运行得更好
Edit Changed the question编辑改变了问题
Its basically this now, it kinda works but I would like to have a better alternative.现在基本上是这样,它有点工作,但我想要一个更好的选择。
$getjson = null;
for($i =0; i < 10; $i++){
try{
$getjson = json_decode(file_get_contents('url'));
if(array_key_exists('index', $getjson)) break;
}catch(\Exception $e){}
}
return $getjson;
You say your code runs, but returns null if it does not read anything.您说您的代码运行,但如果它没有读取任何内容,则返回 null。 The below code will avoid that specific scenario.
下面的代码将避免这种特定情况。
$get = null;
while($get == null || $get === false) {
$get = file_get_contents('url');
}
return json_decode($get);
NOTE: This code can technically be an endless loop, assuming it constantly evaluates this way.注意:此代码在技术上可以是一个无限循环,假设它不断地以这种方式评估。 It would be very advisable to have some kind of check to ensure that the script isn't killed by the web server prematurely, and that it does not continue running forever.
这将是非常可取的有某种检查,以确保脚本不会由Web服务器打死过早,而且它不会继续运行下去。 I would have a set limit for how many times you're actually supposed to keep trying to fetch, and run that as a for-loop instead.
我会对您实际上应该继续尝试获取的次数设置限制,并将其作为 for 循环运行。 Then make sure to have a fallback if all iterations still failed.
如果所有迭代仍然失败,请确保有一个回退。
Something like this would be more advisable:这样的事情会更可取:
$get = null;
$limit = 100;
$i = 0;
do {
$get = file_get_contents('url');
$i++;
} while(($get == null || $get === false) && $i < $limit);
return json_decode($get);
Finally, if you don't like do-while, you can do it with a single for as well.最后,如果你不喜欢 do-while,你也可以用一个 for 来做。
$get = null;
for($i = 0; ($get == null || $get === false) && $i < $limit; $i++) {
$get = file_get_contents('url');
}
return json_decode($get);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.