我在尝试获得siteadvisor.com评分时第18行收到错误。错误消息显示"PHP Fatal error: Call to a member function hasAttribute() on a non-object"
。我已经包含了我用来获得siteadvisor.com评级的ull php代码。
public function getSiteAdvisor($domain)
{
try
{
$callback_url = "http://www.siteadvisor.com/sites/" . $domain;
$curl_response = $this->curl->get($callback_url);
if ($curl_response->headers['Status-Code'] == "200") {
libxml_use_internal_errors(TRUE);
$this->dom_doc->loadHTML($curl_response);
libxml_use_internal_errors(FALSE);
$xpath = new DOMXPath($this->dom_doc);
$tmp = $xpath->query('/html/body//div[@id="siteVerdict"]//img')->item(0);
if ($tmp->hasAttribute('src')) {
$tmp = $tmp->getAttribute('src');
if (stripos($tmp, "green") !== false) {
$siteadvisor_rating = 1;
} elseif (stripos($tmp, "yellow") !== false) {
$siteadvisor_rating = 2;
} elseif (stripos($tmp, "red") !== false) {
$siteadvisor_rating = 3;
} else {
$siteadvisor_rating = 0;
}
} else {
$siteadvisor_rating = 0;
}
} else {
$siteadvisor_rating = 0;
}
$response = array(
'status' => 'success',
'data' => array(
'siteadvisor' => (int)$siteadvisor_rating
)
);
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
答案 0 :(得分:1)
我认为你在xpath查询上遇到了问题(就像Gordon所说的那样):然后改为定位alt=""
属性。
$domain = 'google.com';
$callback_url = "http://www.siteadvisor.com/sites/" . $domain;
// i know you know what do to just you can just adjust this
$curl_response = file_get_contents($callback_url);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($curl_response);
libxml_use_internal_errors(true);
$xpath = new DOMXpath($dom);
$siteadvisor_rating = null;
$img_rating = $xpath->query('//div[@id="siteVerdict"]/div/img');
if($img_rating->length > 0) {
// haystack
if($img_rating->item(0)->hasAttribute('alt')) {
$img_rating = $img_rating->item(0)->getAttribute('alt');
} elseif ($img->item(0)->hasAttribute('src')) {
$img_rating = $img_rating->item(0)->getAttribute('src');
}
if(stripos($img_rating, 'green') !== false) {
$siteadvisor_rating = 1;
} elseif(stripos($img_rating, '') !== false) {
$siteadvisor_rating = 2;
} elseif(stripos($img_rating, 'red') !== false) {
$siteadvisor_rating = 3;
} else {
$siteadvisor_rating = 0;
}
echo $siteadvisor_rating; // should be 1 for google :)
}
else {
// no node is found
}