Home » Php » member function error in data extraction

member function error in data extraction

Posted by: admin October 26, 2017 Leave a comment

Questions:

I am trying get data from a external source but i can’t get the data and i am facing this error.

Notice: Trying to get property of non-object in E:\xampp\htdocs\test\merit-list.php on line 38
Fatal error: Call to a member function find() on null in E:\xampp\htdocs\test\merit-list.php on line 39

Here is my code

<?php
            require('resources/inc/simple_html_dom.php');
            $linksrc = 'http://58.65.172.36/Portal/WebSiteUpdates/Achievements.aspx';
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => $linksrc,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 3000,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
            ));
            $file = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);
            $dom = new simple_html_dom();
            $dom->load($file);
            $doctorDivs = $dom->find("table#Farooq", 0)->children();
            $doctors = array();
            foreach($doctorDivs as $div){
                $doctor = array();

                // line 38
                $image = $doctor["image"] = $div->find('img', 0)->src; 
                $details = $div->find('tr', 0)->find("td");
                $name = $doctor["name"] = trim($details[1]->plaintext);
                $spec = $doctor["desc"] = trim($details[2]->plaintext);

                $doctors[] = $doctor;
                echo $image;
                echo $name;
                echo $spec;
            }       

        ?>
Answers:

The problem is that the first row of the table doesn’t have an <img>, because it’s the row of headings, so $div->find("img", 0) returns null. You get the first error when you try to access null->src.

The second error is because $div is the <tr> element. $div->find("tr") searches the children of $div, it doesn’t include $div itself, so it always returns null. Also, this code won’t work in the heading row, either, because it contains <th> rather than <tr> elements.

You could just skip over the heading row by putting:

array_shift($doctorDivs);

before the foreach loop. This will remove the first element of the array.

And change $details to :

$details = $div->find("td");