开发者

Using simplexml_load_file to pull from tumblr - timing out every time

My site is taking ~45 seconds to load. It's because I'm pulling in some XML from tumblr, but I can't figure out if this is my server's fault, tumbl开发者_如何学运维r's fault, or some other factor. Can I get this script to time out in 5 seconds and echo 'tumblr is down'; instead of just timing out after nearly a minute?

I'm getting this error:

Warning: simplexml_load_file(http://blog.yaytalent.com/api/read?type=post&start=1&num=2) [function.simplexml-load-file]: failed to open stream: Connection timed out in /nfs/c08/h02/mnt/122191/domains/yaytalent.com/html/index.php on line 86

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://blog.yaytalent.com/api/read?type=post&start=1&num=2" in /nfs/c08/h02/mnt/122191/domains/yaytalent.com/html/index.php on line 86

With this code:

<?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>";
?>


ok in this case i can suggest you use cUrl

This way youu can set a timeout and if the page doesnt respond in five seconds you can move on. Documentation

            $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); 

I hope that works for you and goodluck in your learning

UPDATE:

now you can use your simple xml like this:

$xml = simplexml_load_string($response);


You can also do in this way:

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);
}  


curl_setopt(**$s**,CURLOPT_TIMEOUT,5);

Here should be $ch in reply by Ibu I think. But good example anyway! Thank you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜