2011-11-07 57 views
0

我正在尝试使用此方法在我的数据库中读取和存储RSS提要。file_get_contents和有效的xml的响应时间

<?php 
    $homepage = file_get_contents('http://www.forbes.com/news/index.xml'); 
    $xml = simplexml_load_string($homepage,'SimpleXMLElement', LIBXML_NOCDATA); 
    echo '<pre>'; 
    print_r('$xml'); 
?> 

但是:

1. How can I check if `$homepage` contains a valid XML file or not? 

2. I'm want to know how much time its taken to call if the url is valid XML file 

$homepage = file_get_contents('http://www.forbes.com/news/index.xml');

使用try和catch异常..

+0

@Brendan龙..感谢先生,以正确的方式解释我的要求。 – omnath

回答

4

尝试是这样的

$start = microtime(true); 
$homepage = file_get_contents('http://www.forbes.com/news/index.xml'); 
$end = microtime(true); 

$duration = $end - $start; 

try { 
    libxml_use_internal_errors() ; 
    $xml = new SimpleXMLElement($homepage, LIBXML_NOCDATA); 
} catch (Exception $ex) { 
    // error parsing XML 
    throw $ex; 
} 

编辑:您可以将file_get_contents()通话和SimpleXMLElement创作甚至合并成使用

$xml = new SimpleXMLElement('http://www.forbes.com/news/index.xml', 
    LIBXML_NOCDATA, true); 

一行虽然你周围的线条包裹的任何时间将包括HTTP检索解析

+0

警告:SimpleXMLElement :: __ construct()[simplexmlelement .-- construct]:I/O警告:无法加载外部实体“<?xml version =”1.0“?><?xml-stylesheet type =”text/xsl“ href =“/ scripts/rss/rss_transformer.xsl”?> – omnath

+0

先生,我得到了这段代码的时间,但在接下来的部分我有这个错误,我上面提到.. – omnath

+0

@omnath我无法复制该错误(PHP 5.3.6)。你使用的是什么版本的PHP? – Phil

-1

以下的代码只是工作精细。试试吧,

$homepage = file_get_contents('http://www.forbes.com/news/index.xml'); 
$xml = simplexml_load_string($homepage,'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS); 
echo "<pre>"; 
print_r($xml); 
echo "</pre>"; 

谢谢。