0

我正在尝试使用此方法在我的数据库中读取和存储 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');

使用 try 和 catch 异常..

4

2 回答 2

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 检索解析

于 2011-11-07T05:29:33.753 回答
-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>";

谢谢。

于 2011-11-07T05:36:22.963 回答