I'm trying to read and store an RSS feed in my database using this method.

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

But:

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

using try and catch exceptions..

有帮助吗?

解决方案

Try something like this

$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: You can even combine the file_get_contents() call and SimpleXMLElement creation into one line using

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

though any timing you wrap around that line will include HTTP retrieval and parsing

其他提示

Below code will just works fine. Try it,

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

Thanks.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top