我的网站需要45秒的时间才能加载。这是因为我从tumblr中提取了一些XML,但是我不知道这是我的服务器的错误、tumblr的错误还是其他因素。我能让这个脚本在5秒内超时,回显'tumblr关闭‘,而不是仅仅在将近一分钟之后超时吗?
我得到了一个错误:
警告: simplexml_load_file(http://blog.yaytalent.com/api/read?type=post&start=1&num=2) Function.simplexml-load文件:打开流失败:第86行的simplexml_load_file(http://blog.yaytalent.com/api/read?type=post&start=1&num=2)超时 警告: simplexml_load_file() Function.simplexml-load文件: I/O警告:在第86行的/nfs/c08/h02/mnt/122191/domains/yaytalent.com/html/index.php中加载外部实体"http://blog.yaytalent.com/api/read?type=post&start=1&num=2“失败
使用此代码:
<?php
$request_url = "http://blog.yaytalent.com/api/read?type=post&start=1&num=2";
$xml = simplexml_load_file($request_url);
$title = $xml->posts->post->{'regular-title'};
$post = $xml->posts->post->{'regular-body'};
$link = $xml->posts->post['url'];
$small_post = substr($post,0,270);
echo "<h2><a target=frame2 href='".$link."'>$title</a></h2>";
echo "<p>$small_post... <a target=frame2 href='$link'>Read More</a></p>";
?>
发布于 2011-05-11 05:36:36
好的,在这种情况下,我可以建议您使用cUrl
这样你就可以设置一个超时,如果页面在5秒钟内没有响应,你可以继续前进。文档
$url = "http://blog.yaytalent.com/api/read?type=post&start=1&num=2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
curl_setopt($s,CURLOPT_TIMEOUT,5); // TIME OUT is 5 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
我希望这对你和古德勒克的学习都有帮助。
更新:
现在您可以像这样使用简单的xml:
$xml = simplexml_load_string($response);
发布于 2014-05-09 14:37:20
你也可以这样做:
function simplexml_load_file_from_url($url, $timeout = 20){
$context = array('http' => array('timeout' => (int)$timeout));
$data = file_get_contents($url, false, stream_context_create($context));
if(!$data){
trigger_error('Cannot load data from url: ' . $url, E_USER_NOTICE);
return false;
}
return simplexml_load_string($data);
}
发布于 2014-09-03 11:32:54
curl_setopt(**$s**,CURLOPT_TIMEOUT,5);
我想这应该是伊布回复的$ch。但无论如何都是好榜样!谢谢!
https://stackoverflow.com/questions/5959595
复制相似问题