Set time out on simplexml_load_file

后端 未结 3 586
忘了有多久
忘了有多久 2020-12-20 21:51

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 loa

相关标签:
3条回答
  • 2020-12-20 21:59

    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);
    }
    
    0 讨论(0)
  • 2020-12-20 22:01

    This is what I got 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);
    
       if (!$xml) {
    
           $xml = simplexml_load_file('content/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 {
    
           $myFile = "content/backUpXml.xml";
           $fh = fopen($myFile, 'w') or die("can't open file");
           $stringData = $xml;
           fwrite($fh, $stringData);
           fclose($fh);
    
           $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 />';
           }
        }
    
        ?>
    
    0 讨论(0)
  • 2020-12-20 22:24

    From php.net:

    <?php
    $fp = fsockopen("www.example.com", 80);
    if (!$fp) {
         echo "Unable to open\n";
    } else {
    
        fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
        stream_set_timeout($fp, 2);
        $res = fread($fp, 2000);
    
        $info = stream_get_meta_data($fp); //I think this is what you need.
        fclose($fp);
    
        if ($info['timed_out']) { //So you can check this variable.
            echo 'Connection timed out!';
        } else {
            echo $res;
        }
    
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题