如果没有重定向的URL,我的getRedirect()
将失败。但是我想检查数组中的URL。
function getRedirect($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$data = curl_exec($ch);
$domd=@\DOMDocument::loadHTML($data);
$xp=new \DOMXPath($domd);
$location=$xp->query("//meta[@http-equiv='REFRESH']")->item(0)->getAttribute("content");
$location=substr($location,stripos($location,'URL=')+4);
curl_close($ch);
return $location;
}
错误说:Call to a member function getAttribute() on null
我尝试了以下类似操作,但没有帮助。
if ($location=$xp->query("//meta[@http-equiv='REFRESH']")->item(0)->getAttribute("content") !== false) {
$location=substr($location,stripos($location,'URL=')+4);
curl_close($ch);
return $location;
} else {
return true;
}
如果所有URL都被重定向,则函数起作用。我该如何解决这个问题?
答案 0 :(得分:1)
在假定存在任何匹配元素之前,应检查XPath query()
结果的length
例如
curl_close($ch); // this can go immediately after curl_exec()
$metaTags = $xp->query("//meta[@http-equiv='REFRESH']");
if ($metaTags->length > 0) {
$location = $metaTags->item(0)->getAttribute('content');
return substr($location, stripos($location,'URL=') + 4);
}
return true; // or return whatever makes sense if there's no `<meta>` tag