Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

php - Set time out on simplexml_load_file

I have this script which outputs an rss feed. Want I want to do is have it attempt to reach the rss url for something like 5 sec tops, and if it cannot then I want it to load a backup xml doc that is on the server. This is what I have and it is not working:

 <?php

 include '../php/connect.php';
 $metaData = mysql_query("SELECT * FROM `siteinfo`") or die("couln't find table :(");
 $displayData = mysql_fetch_assoc($metaData);
 $url = $displayData['status'];
 $xml = file_get_contents($url);

 stream_set_timeout($xml, 5);

if ($xml == FALSE) {

   $xml = simplexml_load_file('backUpXml.xml');

   foreach ($xml->channel->item as $item) {
      echo '<a href="'.$item->guid.'" alt="'.$item->title.'" target="_blank">',   substr($item->title, 0, 62), '...</a><br /><span>', substr($item->pubDate, 4, 18),'</span><br /><hr /><br />';
   }
}  else {

   $xml = simplexml_load_file($url);

   foreach ($xml->channel->item as $item) {
        echo '<a href="'.$item->guid.'" alt="'.$item->title.'" target="_blank">', substr($item->title, 0, 62), '...</a><br /><span>', substr($item->pubDate, 4, 18),'</span><br /><hr /><br />';
   }
}

 ?>

I am getting a time out error and that is all. Any insight would be great!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a far better solution pointed out by @AnthonySterling here:

function simplexml_load_file_from_url($url, $timeout = 5){
  $opts = array('http' => array('timeout' => (int)$timeout));
  $context  = stream_context_create($opts);
  $data = file_get_contents($url, false, $context);
  if(!$data){
    trigger_error('Cannot load data from url: ' . $url, E_USER_NOTICE);
    return false;
  }
  return simplexml_load_string($data);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...