Jump to content

simpleXML loading from URL problem


edzillion

Recommended Posts

my setup is this

I have a php file that displays prices, it calls another php file that gets the xml file from a URL:

 

pricefeed.php:

<?php

$fileUrl = "http://someurl.com/prices.xml";
$AgetHeaders = @get_headers($fileUrl);

if (preg_match("|200|", $AgetHeaders[0])) {
	// file exists
	echo"file exists";
	readfile($fileUrl);
} 
else 
{
	// file doesn't exist
	echo"file doesn't exist";
	return false;
}
?>

If I run this when the url is unavailable I get "file doesn't exist", but I can't figure out how to call this file without a parsing error if the file is unavailable.

 

The calling line:

$xml = simplexml_load_file('http://localhost/scripts/pricefeed.php');

 

Gives the error:

Warning: simplexml_load_file() [function.simplexml-load-file]: http://localhost/scripts/pricefeed.php:1: parser error : Start tag expected, '<' not found in C:\xampp\htdocs\prices.php on line 17

 

If I get rid of the "file exists" echoes from the pricefeed.php file I get

Document is empty in C:\xampp\htdocs\prices.php on line 17

 

Any ideas?

TIA

Ed

 

Link to comment
https://forums.phpfreaks.com/topic/95936-simplexml-loading-from-url-problem/
Share on other sites

true.

So pricefeed returns false when the file doesn't exist.

So how do I handle this error without outputting a php error?

I can't seem to get a try catch statement to catch the exception.

 

try {
   $xml = simplexml_load_file('http://localhost/scripts/pricefeed.php');
   } catch (Exception $e) {
   // handle the error
   echo $e->getMessage();
}

 

Just returns the error:

Warning: simplexml_load_file() [function.simplexml-load-file]: http://localhost/scripts/pricefeed.php:1: parser error : Start tag expected, '<' not found in C:\xampp\htdocs\wpgoldprices.php on line 17

Hi,

 

Or you can simply do this:

 

<?php

$fileUrl = "http://someurl.com/prices.xml";
$AgetHeaders = @get_headers($fileUrl);

if (preg_match("|200|", $AgetHeaders[0])) {
	// file exists
	echo"file exists";
	readfile($fileUrl);
} 
else 
{
	// file doesn't exist
	echo"<error>Cannot read file</error>";
	return false;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.