【问题标题】:Using simplexml_load_file to pull from tumblr - timing out every time使用 simplexml_load_file 从 tumblr 中提取 - 每次都超时
【发布时间】:2011-08-23 00:12:22
【问题描述】:

我的网站加载大约需要 45 秒。这是因为我从 tumblr 中提取了一些 XML,但我不知道这是我的服务器的错、tumblr 的错还是其他一些因素。我可以让这个脚本在 5 秒内超时并回显“tumblr 已关闭”吗?而不是在将近一分钟后超时?

我收到此错误:

警告:simplexml_load_file(http://blog.yaytalent.com/api/read?type=post&start=1&num=2) [function.simplexml-load-file]:无法打开流:/nfs 中的连接超时/c08/h02/mnt/122191/domains/yaytalent.com/html/index.php 在第 86 行

警告:simplexml_load_file() [function.simplexml-load-file]:I/O 警告:无法加载外部实体“http://blog.yaytalent.com/api/read?type=post&start=1&num=2 " 在 /nfs/c08/h02/mnt/122191/domains/yaytalent.com/html/index.php 第 86 行

使用此代码:

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

【问题讨论】:

  • 如果您拉取的文档的更改频率不是太频繁,您可以将其保存在数据库表中并使用 cron 或调度程序不时更新它
  • Ibu - 谢谢,但我是一名具有一些前端技能的设计师。写这样的东西在我头上。

标签: php performance simplexml tumblr


【解决方案1】:

好的,在这种情况下我可以建议你使用 cUrl

这样你可以设置一个超时,如果页面在五秒内没有响应,你可以继续。 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); 

希望对你有用,祝你学习顺利

更新:

现在您可以像这样使用您的简单 xml:

$xml = simplexml_load_string($response);

【讨论】:

  • 这似乎现在可以工作了,我想也许是 Tumblr API 首先导致了这个问题。我的原始代码又可以工作了。
  • 很好,就像你现在一样,cUrl 是 simplexml_load_file() 的更好替代品,它使用与 file_get_contents 类似的方法。 cUrl 也更快
【解决方案2】:

你也可以这样做:

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

【讨论】:

    【解决方案3】:
    curl_setopt(**$s**,CURLOPT_TIMEOUT,5);
    

    我认为这里应该是 Ibu 的 $ch 回复。但无论如何都是好例子!谢谢!

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      相关资源
      最近更新 更多