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.
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 orfalse
on failure. However, if theCURLOPT_RETURNTRANSFER
option is set, it will return the result on success,false
on failure.
From the documentation :
mixed find ( string $selector [, int $index] )
Find children by the CSS selector. Returns the Nth element object if index is set, otherwise, return an array of object.
so in your case , the returned value is saved in $kungtext_class, the error you have here can be :
1 - the find call return an array , so you have to do that :
foreach($kungtext_class as $element){
echo $element->innertext;
}
2- the find call don't find any element that have the class kungtext so it return null and it's normal that the innertext throw error .
Your code will work correctly onyl if the find method return only one element from the dom that have the class kungtext .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.