Php 如何中断';时间太长了?
如果simplexml_load_文件的加载时间太长和/或无法访问(有时包含xml的站点会宕机),我希望停止该文件,因为我不希望我的站点在它们没有启动时完全滞后 我自己也试过一点,但没有成功Php 如何中断';时间太长了?,php,xml,windows,function,Php,Xml,Windows,Function,如果simplexml_load_文件的加载时间太长和/或无法访问(有时包含xml的站点会宕机),我希望停止该文件,因为我不希望我的站点在它们没有启动时完全滞后 我自己也试过一点,但没有成功 提前非常感谢您的帮助 您应该使用流上下文和超时选项以及文件获取内容 $context = stream_context_create(array('http' => array('timeout' => 5))); //<---- Setting timeout to 5 seconds.
提前非常感谢您的帮助 您应该使用
流上下文
和超时
选项以及文件获取内容
$context = stream_context_create(array('http' => array('timeout' => 5))); //<---- Setting timeout to 5 seconds...
$xml_load = file_get_contents('http://yoururl', FALSE, $context);
$xml = simplexml_load_string($xml_load);
不能让任意函数在指定时间后退出。相反,您可以先尝试加载URL的内容,如果加载成功,则继续处理脚本的其余部分 有几种方法可以实现这一点。最简单的方法是将
file\u get\u contents()
与流上下文集一起使用:
$context = stream_context_create(array('http' => array('timeout' => 5)));
$xmlStr = file_get_contents($url, FALSE, $context);
$xmlObj = simplexml_load_string($xmlStr);
或者,您可以通过以下函数使用流上下文:
$context = stream_context_create(array('http' => array('timeout' => 5)));
libxml_set_streams_context($context);
$xmlObj = simplexml_load_file($url);
function simplexml_load_file_from_url($url, $timeout = 5)
{
$context = stream_context_create(
array('http' => array('timeout' => (int) $timeout))
);
$data = file_get_contents($url, FALSE, $context);
if(!$data) {
trigger_error("Couldn't get data from: '$url'", E_USER_NOTICE);
return FALSE;
}
return simplexml_load_string($data);
}
您可以将其包装为一个漂亮的小函数:
$context = stream_context_create(array('http' => array('timeout' => 5)));
libxml_set_streams_context($context);
$xmlObj = simplexml_load_file($url);
function simplexml_load_file_from_url($url, $timeout = 5)
{
$context = stream_context_create(
array('http' => array('timeout' => (int) $timeout))
);
$data = file_get_contents($url, FALSE, $context);
if(!$data) {
trigger_error("Couldn't get data from: '$url'", E_USER_NOTICE);
return FALSE;
}
return simplexml_load_string($data);
}
可选地,可以考虑使用(默认情况下可用)。使用cURL的好处是可以对请求和如何处理响应进行细粒度的控制
您还可以使用libxml\u set\u streams\u context($context)
在调用simplexml\u load\u file
以实现此目的之前。顺便说一句,+1表示指向正确的方向。也许你可以按照Amal的建议添加libxml\u set\u streams\u context
?@hek2mgl,我从未尝试过。我希望如果Amal编辑这个答案。@AmalMurali也许你可以完成这个协作工作?柏林向印度致意!:)@hek2mgl:我不想从根本上改变这个答案,所以我添加了。可能是重复的