if($xml->getElementsByTagName($elmnt) && $xml->getElementsByTagName($elmnt)->length > 0)
This line is intended to check for errors. All I want is to, instead of breaking the entire page, make a legible error message. It is included in a function designed to stop all related processes on failure and continue displaying the rest of the page if it doesn't work, since the page layout does not depend on whether or not this function succeeds.
Fatal error: Call to a member function getElementsByTagName() on a non-object in file.php on line 100
How do I actually check to make sure that the DOMDocument in question has the element without it throwing the error above? I've tried using just the first condition or the second condition.
var_dump($xml);
object(DOMDocument)#3 (1) {
["preserveWhitespace"]=>
bool(false)
}
If you use simplexml_load_file to load the file, it will either return with a successfull load or it will return false on failure. The error you are getting signifies that the variable $xml is not an object, which means that when you tried to load the xml file onto the variable, it didn't do it successfully.
If before you do the getElementsByTagName($elmnt) you make sure $xml is not false, you shouldn't get the error Fatal error: Call to a member function getElementsByTagName() on a non-object in file.php on line 100
if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');
if($xml){
print_r($xml);
}
} else {
exit('Failed to open test.xml.');
}
Your problem is that $xml is not an object, you have to check that first:
if ($xml && ($obj = $xml->getElementsByTagName($elmnt)) && $obj->length > 0) {
// you should be good as this point
}
You can also use !empty($xml) instead of just $xml if there is a possibility that $xml is undefined.
Related
I'm trying to read html element
try{
$contact = trim($wrapper->children(1)->children(1)->children(1)->children(0)->innertext);
}catch(Exception $e){
echo "Some Error";
}
Now script works normally if $wrapper has children.
But, if $wrapper dosen't have children script stops giving the following error.
<b>Fatal error</b>: Call to a member function children() on a non-object in <b>C:\path\sc.php</b> on line <b>30</b><br />
but, as try catch is their its not expected to stop.
I need to continue the script executing, even if children is not found.
You cannot catch fatal errors in PHP (You can register a shutdown function, but execution will still be stopped). You will need to make some checks to ensure that the children exist.
var $child1 = $wrapper->children(1);
if ( !is_object($child1) )
return;
var $child2 = $child1->children(1);
...
Alternatively, you can ignore the exception by adding a preceding '#':
$contact = #$wrapper->children(1)->children(1)->children(1)->children(0)->innertext;
I have this error when parsing html
my code is like this
$html = new \simple_html_dom();
$html->load_file($url);
$type = gettype($html);
$this->output->writeln("check point1:" . $type); // it says 'object'
$class = get_class($html);
$this->output->writeln("check point2:" . $class); // it says 'simple_html_dom'
foreach($html->find('a') as $element){
//do something here.
}
then this code shows this error sometims.
PHP Fatal error: Call to a member function find() on a non-object
error
even when error happens $html is correctly fetched (I check in two check points)
This error is similar to this article though, no slution is revealed.
Please help me
If I include a file in to php. If there is any fatal error in that php then is there any way to skip that .
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on somefile.php
?>
I need to include this somefile.php file. It may return fatal error
for some host. I want to skip this file for those host.
Please Advice me.
With this, you can define your own continuation function that will take over in case of a fatal error. This uses register_shutdown_function() to intercept the fatal error.
Usage:
function my_continuation_func($filename, $arg2) {
// On fatal error during include, continue script execution from here.
// When this function ends, or if another fatal error occurs,
// the execution will stop.
}
include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();
If a fatal error occurs (like a parse error), script execution will continue from my_continuation_func(). Otherwise, include_catch() returns true if there was an error during parsing.
Any output (like echo 'something';) from the include() is treated as an error. Unless you enabled output by passing true as the third argument to include_try().
This code automatically takes care of possible working directory changes in the shutdown function.
You can use this for any number of includes, but the second fatal error that occurs cannot be intercepted: the execution will stop.
Functions to be included:
function include_try($cont_func, $cont_param_arr, $output = false) {
// Setup shutdown function:
static $run = 0;
if($run++ === 0) register_shutdown_function('include_shutdown_handler');
// If output is not allowed, capture it:
if(!$output) ob_start();
// Reset error_get_last():
#user_error('error_get_last mark');
// Enable shutdown handler and store parameters:
$params = array($cont_func, $cont_param_arr, $output, getcwd())
$GLOBALS['_include_shutdown_handler'] = $params;
}
function include_catch() {
$error_get_last = error_get_last();
$output = $GLOBALS['_include_shutdown_handler'][2];
// Disable shutdown handler:
$GLOBALS['_include_shutdown_handler'] = NULL;
// Check unauthorized outputs or if an error occured:
return ($output ? false : ob_get_clean() !== '')
|| $error_get_last['message'] !== 'error_get_last mark';
}
function include_shutdown_handler() {
$func = $GLOBALS['_include_shutdown_handler'];
if($func !== NULL) {
// Cleanup:
include_catch();
// Fix potentially wrong working directory:
chdir($func[3]);
// Call continuation function:
call_user_func_array($func[0], $func[1]);
}
}
Fatal means fatal ...
There is no way to recover from a fatal error.
You can use register_shutdown_function.
<?php
function echoOk()
{
echo "OK";
}
register_shutdown_function(function ()
{
$error = error_get_last();
// to make sure that there is any fatal error
if (isset($error) &&
($error['type'] == E_ERROR
|| $error['type'] == E_PARSE
|| $error['type'] == E_COMPILE_ERROR
|| $error['type'] == E_CORE_ERROR))
{
echoOk();
}
});
include "somefile.php";
echoOk();
But you can do it only once. Any further fatal error will stop execution.
PHP won't tolerate with Fatal Errors. Best to check the included file and solve it.
Actually, you can try looking at register-shutdown-function, but it's not recommended to run away from your problems.
Yes, there is. It can be done through a simple if statement
You Have:
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on
?>
Try This:
<?php
if(include "somefile.php"){
// echo do something if success
}else{
echo "OK";
}
edit: I missed the word fatal. As stated, you can't recover from a fatal error. If it is just an exception the hastly writen response below will work.
Including another php module is the same as that code being inserted inline, so a simple try-catch statement should work:
<?php
try {
include "somefile.php";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "OK";
?>
Try to set a set_error_handler() function that doesn't die on fatal errors, but instead Apache crashed. In other words, PHP needs to die so that the system doesn't.
See this LINK
Fatal Error means there is something seriously wrong with the including code. As #Orangepill said there is no way to stop this fatal error message popping up. Please go through your coding and find the error.
<?php
try {
$attrs = $xml->attributes();
$code = $attrs['_Code'];
}
catch (Exception $e)
{
$code = '';
}
?>
Gets me:
Fatal error: Call to a member function attributes() on a non-object on
line 6
Why am I getting errors thrown on code wrapped in a try-catch??
NOTE: It is possible to avoid this error by using the following code. (The question is not about avoiding the error, but why it's not being caught- still I thought I'd share the non-erroring code anyway)
if (is_object($xml) && method_exists($xml,'attributes')) {
$attrs = $xml->attributes();
$code = !empty($attrs['_Code'])?$attrs['_Code']:'';
}
else {
$code = '';
}
PHP fatal errors cannot be caught. I don't know the specifics of what you're doing, but you'll have to figure out some other way to test whether $xml->attributes() will work or not.
Also, swallowing every error and not logging it anywhere is bad practice because when stuff starts breaking you won't have any idea of why.
try/catch only works for exceptions, not parse errors. You have to test to make sure that $xml has an attributes method to avoid such an error (could be called a null pointer, but not exactly).
I am a beginner in PHP and I have a similar problem to that handled in:
Good error handling with file_get_contents
In simple_html_dom.php, there is a function called load_file, which is:
function load_file() {
$args = func_get_args();
$this->load(call_user_func_array('file_get_contents', $args), true);
}
In my PHP script, I use this function as:
$html->load_file($link);
When I try to load a broken link, I get a warning message on my output display like:
Warning: file_get_contents(http://www.yurowdesigns.com/UkraineSIG/test.asp) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/yurow/wwwroot/yurowdesigns.com/programs/simple_html_dom.php on line 568
I would like to re-route this and similar error messages to an error.log file on my website rather than having it on my output display.
I naively tried to adapt the answer given in
Good error handling with file_get_contents
to my problem by adding the the function fget_contents() to my copy of simple_html_dom.php.
function fget_contents() {
$args = func_get_args();
// the # can be removed if you lower error_reporting level
$contents = #call_user_func_array('file_get_contents', $args);
if ($contents === false) {
throw new Exception('Failed to open ' . $file);
} else {
return $contents;
}
}
And changed line 568 in load_file to read:
$this->load(call_user_func_array('fget_contents', $args), true);
But now, when I run my PHP script, I get a new error message:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'fget_contents' not found or invalid function name in /home/yurow/wwwroot/yurowdesigns.com/programs/simple_html_dom.php on line 568
Which means that simple_html_dom.php does not recognize the function 'fget_contents'
Where did I go wrong? How can I fix it?
Use the following code :
function load_file() {
try{
$args = func_get_args();
$this->load(call_user_func_array('file_get_contents', $args), true);
} catch(Exception e) {
print_r(e);
}
}
Here as you see it has try and catch block that will handle the errors.
To do that, in your PHP files, set them up to hide errors from being displayed. Use ini_set('display_errors','1'); and then log your errors using error_log or hopefully your default php.ini config already logs errors using the error_log string