使脚本部分超时并允许其余部分继续
我有一个在我的主页上运行的小部件,它从外部源加载 xml 数据。我想在 x 秒后使 xml 加载超时(最近另一个站点出现了加载问题)。这是我到目前为止所拥有的功能。我不知道如何使计时器与 simplexml_load_file()
无效。
我走在正确的轨道上吗?有办法让这项工作发挥作用吗?或者有更好的方法来做到这一点吗?如果超时,我仍然需要页面的其余部分继续加载,所以我不能使用 set_time_limit()
,因为这将结束所有脚本执行,对吧?
function timer($end) {
$count = 0;
while($end > $count) {
sleep(1);
$count++;
}
return true;
}
$we = simplexml_load_file('http://forecast.weather.gov/MapClick.php?lat=44.08920&lon=-70.17250&FcstType=xml');
if(timer(3)) return;
I have a widget that runs on my homepage which is loading xml data from an external source. I want to timeout the xml load after x seconds (lately the other site has been having load issues). Here is the function I have so far. I can't figure out how to make the timer ineract with the simplexml_load_file()
.
Am I on the right track? Is there a way to make this work? Or is there a better way to do this? If this does timeout, I still need the rest of the page to continue loading, so I can't use set_time_limit()
, because that will end all script execution, right?
function timer($end) {
$count = 0;
while($end > $count) {
sleep(1);
$count++;
}
return true;
}
$we = simplexml_load_file('http://forecast.weather.gov/MapClick.php?lat=44.08920&lon=-70.17250&FcstType=xml');
if(timer(3)) return;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,您需要为
simplexml_load_file()
设置超时。您无法具体设置它,但您可以在使用该函数之前全局设置它(对于所有基于套接字的流):So you want to set a timeout for
simplexml_load_file()
. You can't set it specifically, but you can just set it globally (for all socket based streams) before using the function:我会使用 CURL 而不是直接加载 URL...
I would use CURL instead of loading the URL directly...
您可以首先使用一些阻塞或更可靠的函数(例如 fopen、fsockopen 或 curl,选择您可以使用的最佳函数)读取文件的内容,然后将内容传递给 simplexml_load_string 而不是 simplexml_load_file
You could first read the content of the file with some blocking or more reliable function (like fopen, fsockopen or curl, choose the best you can use) and then pass the content to simplexml_load_string instead of simplexml_load_file