Domanda

I'm reading a rss feed and check I'm want to know how much time its taken to call

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

for this I'm using

 <?php

$start = microtime(true);
$homepage = file_get_contents('http://www.fohgggrbes.com/news/index.xml');
 $end = microtime(true);
 $dur=$end-$start;
 echo $dur;
  $xml = simplexml_load_string($homepage,'SimpleXMLElement', LIBXML_NOCDATA);
  echo '<pre>';
?>

but my requirement is first I check the file is valid xml ,if is it ,then its show response time

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

or if the XML file is not valid then shows error message. I want to use try and catch exceptions.

È stato utile?

Soluzione

Checking whether a URL is valid is a different thing than checking whether the XML is valid. When you try to load an invalid URL, the error is usually something like

failed to open stream: php_network_getaddresses: getaddrinfo failed

However, that error stems from the stream wrapper, while any XML validation is done after that by libxml. Hence, you need to check two different things. Below code will take both into account:

libxml_use_internal_errors(true);
$start = microtime(true);
$rss = @simplexml_load_file(
    'http://www.fohgggrbes.com/news/index.xml',
    'SimpleXMLElement',
    LIBXML_NOCDATA
);
$end = microtime(true);
$errors = array_filter(
    array(error_get_last(), libxml_get_errors()),
    function($val) { return !empty($val); }
);
print_r(empty($errors) ? $end - $start : $errors);
libxml_use_internal_errors(false);

I leave it up to you to wrap that into a class and throw exceptions if you want to use try/catch.

Altri suggerimenti

I suppose you could always submit the retrieved data to the W3C feed validator (http://validator.w3.org/feed/) with CURL once you've fetched it, or send the URL to the validator (which is probably the better approach as you're moving less data around), but processing the returned results may be tricky (the results are a HTML document that's meant to be human-readable rather than machine-readable).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top