file_get_contents和有效xml的响应时间


Response time of file_get_contents and valid xml

我正在尝试使用这种方法在我的数据库中读取和存储RSS提要。

<?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');

试试这样

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

Edit:您甚至可以使用

file_get_contents()调用和SimpleXMLElement创建合并到一行中
$xml = new SimpleXMLElement('http://www.forbes.com/news/index.xml',
    LIBXML_NOCDATA, true);

,尽管在这行周围的任何时间都将包括HTTP检索解析

下面的代码将正常工作。试试吧,

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

谢谢。