Fatal error call to a member function find on a non object in

I am new to php. I getting Fatal error: Call to a member function find() on a non-object error, I included simple_html_dom.php <?php include 'simple_html_dom.php'; $htm = file_get_html('htt...

I am new to php.
I getting

Fatal error: Call to a member function find() on a non-object error,

I included simple_html_dom.php

<?php
include 'simple_html_dom.php';
$htm = file_get_html('http://www.thatscricket.com');

$es = $htm->find('div[class=score_card_display_below_links]');

$value = $es[0]->href;

$link = "http://www.thatscricket.com/$value";

$html = file_get_html('$link');

$scr = $html->find('span');

echo "$scr";
?>

Shankar Narayana Damodaran's user avatar

asked Aug 13, 2013 at 10:33

user2677798's user avatar

1

$html = file_get_html('$link');

This will try to get the literal string '$link' (variables aren’t expanded inside single quoted strings). Which means $html will be null or false.

Since $html isn’t an object you can’t call methods on it.

Use:

$html = file_get_html($link);

You should also always check return types that may be false or null due to failure so that you can fail gracefully.

answered Aug 13, 2013 at 10:37

Jim's user avatar

JimJim

22.2k6 gold badges52 silver badges80 bronze badges

check the var_dump($htm) first, it must be returning null

answered Aug 13, 2013 at 10:37

Nishant's user avatar

NishantNishant

3,5841 gold badge19 silver badges26 bronze badges

$htm = file_get_html('http://www.thatscricket.com');

check var_dump($htm);
I think it returns bool(false)

$html = file_get_html('$link'); 

should be

$html = file_get_html($link);

answered Aug 13, 2013 at 10:36

som's user avatar

somsom

4,6302 gold badges20 silver badges36 bronze badges

I had also the same error I found it solution from php count function like this

if( $htm ){
     $score_card_count = count($htm->find('div[class=score_card_display_below_links]'));
     $score_card_count = trim($score_card_count);
         if( $score_card_count > 0 )
         {
              $es = $htm->find('div[class=score_card_display_below_links]');
              $value = $es[0]->href;
         }
}

I hope it will work fine from this approach my error is fixed.

answered Nov 7, 2014 at 7:40

user3632390's user avatar

Simple Html Dom is a PHP dom manipulator. This library is one of the easiest and most powerful dom manipulator for PHP. In fact, you can even use this to create your own web crawler like what i have done. However, Simple Html Dom library isn’t perfect. Although you are able to do almost everything without a problem using simple htm dom, the most problematic thing that will happen in a complex program would be to have different combination of URL. The combination of a URL is endless and this can cause simple html dom to fail.

I faced this problem with simple html dom where fatal error keep stopping my php crawler using simple html dom. The fatal error always occurs around «call to a member function on a non-object at….» and when I look at the fatal error link being process, it was perfectly fine. In PHP, we cannot really stop a fatal error without using some black magic which not always work. Like many people would have say, prevention is better than cure. Hence, doing a checking to determine whether the variable is an object before proceeding will definitely fixed this problem. If you think like many other people out there, this is most likely what you would have done and bet that it will definitely fix your problem.

$html = file_get_html($url);
if(is_object($html)){
   foreach($html->find('img') as $img){
      //bla bla bla..
   }
}

Well, the above might work in some case but not all. when file_get_html failed, it will return false regardless of 404 or 500 occurs on the other side of the server. Hence, you may do this as well,

$html = file_get_html($url);
if($html){
   foreach($html->find('img') as $img){
      //bla bla bla..
   }
}

But if it still doesn’t solve your problem which it really shouldn’t be able to take care of all cases, you might turn to do the following,

$html = file_get_html($url);
if($html && is_object($html)){
   foreach($html->find('img') as $img){
      //bla bla bla..
   }
}

Well, if this still doesn’t work and your brain is stuck, you might feel lucky this time that you come to this blog of mine.

Simple_Html_Dom Fatal Error Solution

The solution for your problem is actually quite simple but not direct. However, i have tested this with almost few hundred thousands of different URL so i can confirm you that this will definitely solve your fatal error and get rid of the «call to a member function on a non-object» especially when it reaches «find». The solution is simple, using the above example, we will just have to add in a condition where it doesn’t fail and the object was created by simple html dom class but it doesn’t contain any node! In this case, you should write something like the following,

$html = file_get_html($url);
if($html && is_object($html) && isset($html->nodes)){
   foreach($html->find('img') as $img){
      //bla bla bla..
   }
}

In the above example, i uses all the true condition but in my real program i was using all the false condition (is false). But it should still works. I tested this for a few days as the bot was required to run for a few lots of hours before i bang into a fatal error. This is really a wasteful of time. But the solution is rewarding. I hope this help some fellow out there 🙂

  1. Home

  2. PHP Simple HTML DOM Parser [fatal error Call to a member function find() on a non-object ]

47 votes

1 answers

Get the solution ↓↓↓

Anyone knows why I have this error? What am I doing wrong?

<?
include('simple_html_dom.php');

$html = ("http://99designs.pt/logo-design/contests?show=finished");
foreach($html->find('span[class=active.sl_notranslate]') as $aholder) {

echo $aholder . '<br>';
}
?>

Fatal error: Call to a member function find() on a non-object in
../simplehtml.php on line 5

2022-04-23

Write your answer


389

votes

Answer

Solution:

You forgot to add the function namefile_get_html, the code should be like this:

<?php
  include 'simple_html_dom.php';

  $html = file_get_html("http://99designs.pt/logo-design/contests?show=finished");
  foreach($html->find('span[class=active.sl_notranslate]') as $aholder) {

    echo $aholder . '<br>';
  }

?>


Share solution ↓

Additional Information:

Date the issue was resolved:

2022-04-23

Link To Source

Link To Answer
People are also looking for solutions of the problem: object of class stdclass could not be converted to string

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.


About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

HTML

HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/



Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

This fatal error will occur if you attempt to call a function on a variable that is not an object.

For example.

//Attempt to call the function getList.
$test->getList();

If the variable $test above is not an object, then our code with spit out the following error.

Fatal error: Call to a member function getList() on a non-object on line […]

This can happen because of four reasons.

  1. You did not create the object in the first place.
  2. The variable does exist, but it is not an object. In other words, it is an integer, an array or a string.
  3. You did create the object. However, your code is overwriting it or unsetting it at a later stage.
  4. The object in question does not exist inside the current scope. For example, you are attempting to reference the object inside of another function without passing it through as a parameter.

Take the following example of a scope issue.

//Create our object.
$car = new Car();

//Example function.
function test(){
    //Attempt to call the object's drive method.
    $car->drive();
}

//Call the function.
test();

The code above will result in a fatal error. Why? Because the object $car does not exist inside of the scope of the test function.

Consequently, our PHP script will throw a fatal error about how we are attempting to call a member function on a non-object.

To fix this particular error, we will need to pass the $car object in as a function parameter.

//Doing it the right way.
function test($car){ 
    //Attempt to call the object's drive method. 
    $car->drive(); 
}

//Call the function.
test($car);

Using the is_object function.

In some cases, the creation of an object might be outside of your control.

In situations like this, you will need to check if the object exists or not before you attempt to use it. You can do this by using PHP’s native is_object function.

An example of this function in action.

//If $myObject is actually an object.
if(is_object($myObject)){
    //Call the function.
    $myObject->printList();
}

Although the above piece of code will “fix” the fatal error, it does not take into account the fact that the variable might not exist.

In other words, we are still leaving ourselves open to nasty “Undefined Variable” notices.

To fix this, we can use the isset function in conjuction with the is_object function.

//We're expecting an object by the name $myObject
if(isset($myObject) && is_object($myObject)){
    //$myObject exists AND it is an object.
} else{
    //Object was not found
}

The function isset checks to see if the variable exists or not. If it does exist, then the IF statement will check to see if it is an object.

Hopefully, this article helped!

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error c1902 несоответствие диспетчера базы данных программы проверьте установленную копию
  • Fatal error c1859 непредвиденная ошибка предкомпилированного заголовка
  • Fatal error c1853
  • Fatal error c1510 cannot load language resource clui dll
  • Fatal error c1202

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии