Search code examples
phpcurlsimple-html-dom

CURL PHP Trying to get property of non-object


I'm trying to parse an html output that i get through CURL using simple html dom, but I get this error:

Trying to get property 'innertext' of non-object

This is the relevant code:

$output = curl_exec($ch);

if($output === FALSE) {
    echo "cURL Error: " . curl_error($ch);
}

curl_close($ch);

$html = str_get_html($output);
$kungtext_class = $html->find('div[class=kungtext]');
$kungtext = $kungtext_class->innertext;

echo $kungtext;

Output variable is the gathered HTML in text-form that I get from CURL.


Solution

  • Updated answer

    $kungtext_class is giving you an array, you can't access the property because you get a bunch of elements, not only one.

    See the docs http://simplehtmldom.sourceforge.net/manual_api.htm

    mixed find ( string $selector [, int $index] )
    

    Find elements by the CSS selector. Returns the Nth element object if index is set, otherwise return an array of object.

    So your code should be like

    foreach ($html->find('div[class=kungtext]') as $kungtext_class) {
        echo $kungtext_class->innertext;
    }
    

    Or, access index 0 (first element):

    $kungtext_class = $html->find('div[class=kungtext]', 0);
    $kungtext = $kungtext_class->innertext;
    

    Old answer

    curl_exec() by default returns a boolean.

    You need to set CURLOPT_RETURNTRANSFER in the curlopts, it then returns the expected string (on success).

    // Before the curl_exec():
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    

    http://php.net/manual/en/function.curl-exec.php

    Returns true on success or false on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, false on failure.