Response time of file_get_contents and valid xml
-
23-02-2021 - |
Question
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..
Solution
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
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow