Ad

Laravel Correct Php Code Doesnt Work In Class's Function

- 1 answer

this below code work fine without any problem, but after move that into function i get error and doesnt work

Route::get('test', ['as' => 'test', function () {
    $data = 'MYURL';

    $table = [];

    $html = new \Htmldom($data);
    foreach($html->find('tr') as $row) {
        $col_1 = $row->find('td',0)->plaintext;
        $col_2 = "";
        try{
            $col_2= $row->find('td',1)->plaintext;
        }catch (Exception $ignore){}

        $table[] = $col_2;
    }

    $values = array_values($table);
    unset($values[0]);
    unset($values[1]);
    unset($values[5]);
    $values = array_values($values);
    print_r($values);
    /*print_r(\App\Customs\Helpers::get_online_currencies());*/
}]);

My Class:

class Helpers
{
    public static function get_online_currencies(){
        $data = 'MYURL';

        $table = [];
        $html = new \Htmldom($data);

        foreach($html->find('tr') as $row) {
            $col_2 = "";
            try{
                $col_2= $row->find('td',1)->plaintext;
            }catch (Exception $ignore){}

            $table[] = $col_2;
        }

        $values = array_values($table);
        unset($values[0]);
        unset($values[1]);
        unset($values[5]);

        return array_values($values);
    }
}

Error:

ErrorException in Helpers.php line 23: 
Trying to get property of non-object

line 23:

$col_2= $row->find('td',1)->plaintext;

You can test my code.

Ad

Answer

The first and the last row have only 1 column. Assert results of find before fetch data:

    foreach($html->find('tr') as $row) {
        $col_2 = "";
        try{
            $col_2= $row->find('td',1);
        }catch (Exception $ignore){}
        $table[] = $col_2 ? $col_2->plaintext : "";
    }
Ad
source: stackoverflow.com
Ad