simplexml error handling php
I've found a nice example in the php documentation.
So the code is:
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (false === $sxe) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
And the output, as we/I expected:
Failed loading XML
Blank needed here
parsing XML declaration: '?>' expected
Opening and ending tag mismatch: xml line 1 and broken
Premature end of data in tag broken line 1
Catch SimpleXML Exception only?
The problem you have is very local and can be easily handled.
Instead of using
$xml = new SimpleXMLElement($buffer);
(the exception-case is that $buffer = ''
)
You can make use of a function that tells you whether or not loading of the buffer did work w/o throwing an exception:
$xml = simplexml_load_string($buffer);
In case of an error, $xml
will be false. So you don't have the exception problem in the first place.
Additionally I suggest you make the code more stable as well if you're interested in more detailed error handling, like checking preconditions and postconditions for the function call:
if (!is_string($buffer) || !strlen($buffer)) {
throw new UnexpectedValueException("String with length required");
}
$xml = simplexml_load_string($buffer);
if (!$xml) {
throw new UnexpectedValueException('String could not be parsed as XML');
}
This also shows how you can throw the exceptions you like. However as you're only concerned about a single line of code you can just catch any exception and deal with the single error-case you have there:
try {
$xml = new SimpleXMLElement($buffer);
} catch (Exception $e) {
$xml = false;
}
But then, using simplexml_load_string
might be more handy.
Next to that, you can also enable internal error reporting of libxml and find out more about the actual problems when creating the object:
$saved = libxml_use_internal_errors(true);
$xml = simplexml_load_string($buffer);
$errors = libxml_get_errors();
libxml_use_internal_errors($saved);
if (!$xml) {
var_dump($errors); // create and throw a specific exception here based on errors.
}
However, an empty string won't create any error, better take care if it with a precondition check.
Additionally:
- Make the cron-job save to a different filename while donwloading, replacing the file only when ready.
- Open the file read-only.
PHP simplexml_load_file - catch file errors
Using @
is just plain dirty.
If you look at the manual, there is an options parameter:
SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )
All option list is available here: http://www.php.net/manual/en/libxml.constants.php
This is the correct way to suppress warnings:
$xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);
SimpleXML Error Handling
I would just look for existence of $xml->weather->problem_cause
as this seems to only appear in the bad XML.
if (isset($xml->weather->problem_cause)) {
// you have a problem
} else {
// you received data
}
Alternately, you might look for the presence of $xml->weather->forecast_information
as a positive assertion that the data exists.
PHP SimpleXML Error Message
Is it the attributes() method not returning a value? It looks like it may be the $xml->Name that isn't set. Try checking if $xml->Name is set:
if( isset($xml->Name) )
$value = $xml->Name->attributes();
Cron PHP simplexml error
Instead of this path you have:
/usr/bin/php -q /home/******/public_html/******/test2.php
Try using this path:
php /home/******/public_html/******/test2.php
Let me know if it works now!
Error handling in simplexml_load_file
Couple of things that helped me to solve my problem:
$foxs_url_breaking_news = 'http://feeds.news.com.au/public/rss/2.0/fs_breaking_news_13.xml';
$foxs_xml_breaking_news = @simplexml_load_file($foxs_url_breaking_news, 'SimpleXMLElement', LIBXML_NOCDATA);
if(@simplexml_load_file($foxs_url_breaking_news, 'SimpleXMLElement', LIBXML_NOCDATA))
{
foreach($foxs_xml_breaking_news->channel[0]->item as $item)
{
$date = date('Y-m-d H:i:s',strtotime($item->pubDate));
$news->insert(array('source' => 'foxsports',
'headline' => addslashes($item->title),
'timestamp' => $date,
'description' => addslashes($item->description),
'category' => 'Breaking News',
'link' => addslashes($item->link)));
}
}
So: I have used @ in front of simplexml_load_file to avoid error message in case it is unable to load the file
And second: I have the whole "@simplexml_load_file($foxs_url_breaking_news, 'SimpleXMLElement', LIBXML_NOCDATA)" in my IF statement, instead of $foxs_xml_breaking_news. I dont have an idea why is this working and not when i have $foxs_xml_breaking_news in my IF was not working.
I even tried if($foxs_xml_breaking_news === FALSE) but even this did not work for me.
Related Topics
How to Send Emails via Cron Job Usng PHP MySQL
PHP Case-Insensitive In_Array Function
Regular Expression to Collect Everything After the Last /
How to Create Codeigniter Batch Insert Array
MySQL No Connection Could Be Made Because the Target MAChine Actively Refused It
Hide Shipping Methods for Specific Shipping Class in Woocommerce
Preg_Match(); - Unknown Modifier '+'
Setting Value of a HTML Form Textarea
Read a File Backwards Line by Line Using Fseek
How to Sum N Number of Time (Hh:Mm Format)
How to Add New Column to MySQL Table
Save Current Page as HTML to Server
How to Display Image from Database Using PHP
How to Update/Edit a JSON File Using PHP