PHP CURL致命错误:在null上调用成员函数getAttribute()
由于某些原因,当函数中调用的url上没有图像时,我会出现以下错误PHP CURL致命错误:在null上调用成员函数getAttribute(),php,curl,Php,Curl,由于某些原因,当函数中调用的url上没有图像时,我会出现以下错误 Fatal error: Call to a member function getAttribute() on null in .... on line 29 如果他们没有标题,就不会发生这种情况;如果没有元标记,就不会发生这种情况;如果他们没有段落标记,就不会发生这种情况。似乎只有在没有img标签时才会发生。我如何才能使这项工作,以便当没有图像时,它停止吐出错误 <? function file_get_content
Fatal error: Call to a member function getAttribute() on null in .... on line 29
如果他们没有标题,就不会发生这种情况;如果没有元标记,就不会发生这种情况;如果他们没有段落标记,就不会发生这种情况。似乎只有在没有img标签时才会发生。我如何才能使这项工作,以便当没有图像时,它停止吐出错误
<?
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getit($site) {
$parsing = file_get_contents_curl($site);
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($parsing);
$nodes = $doc->getElementsByTagName('title');
$node = $doc->getElementsByTagName('img');
$para = $doc->getElementsByTagName('p');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$firstimage = $node->item(0)->getAttribute('src');
$firstparagraph = $para->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('property') == 'og:description') {
$description = $meta->getAttribute('content'); }
elseif ($meta->getAttribute('name') == 'description') {
$description = $meta->getAttribute('content'); }
else { $descrition = "<p>".implode(' ', array_slice(explode(' ', $firstparagraph), 0, 25))."</p>"; }
if($meta->getAttribute('property') == 'og:image') {
$image = $meta->getAttribute('content');
}
}
if ($image != '') { $image = $image; } else { $image = $firstimage; }
$str .= 'Title: '.$title.' <br/><br/>';
$str .= 'Description: '.$description.' <br/><br/>';
$str .= 'Image: <img src="'.$image.'"><br/><br/>';
echo $str;
}
?>
在获取属性之前使用此检查: if($node->item(0)->hasAttribute('src')) { $firstimage = $node->item(0)->getAttribute('src'); } else { $firstimage = ""; } 如果($node->item(0)->hasAttribute('src')){ $firstimage=$node->item(0)->getAttribute('src'); }否则{ $firstimage=“”; }
在获取属性之前使用此检查: if($node->item(0)->hasAttribute('src')) { $firstimage = $node->item(0)->getAttribute('src'); } else { $firstimage = ""; } 如果($node->item(0)->hasAttribute('src')){ $firstimage=$node->item(0)->getAttribute('src'); }否则{ $firstimage=“”; }
为了便携性、安全性和天知道还有什么,停止使用短标签!我不明白你的意思@hanshenrik。上面发布的代码都没有使用任何短标记。你是特别指使用还是你看到了更多的东西?是的,我指的是那些。它们之所以不好,有很多不同的原因。例如,它们在禁用短标记的服务器上不起作用。如果您移动到一个新的服务器,在那里它们被禁用,并且您有任何硬编码的密码,其他人可能会看到您的源代码和硬编码的密码。而且,它们使通过解析器运行XML文件更容易出错为了可移植性、安全性和天知道的其他原因,停止使用短标记!我不明白你的意思@hanshenrik。上面发布的代码都没有使用任何短标记。你是特别指使用还是你看到了更多的东西?是的,我指的是那些。它们之所以不好,有很多不同的原因。例如,它们在禁用短标记的服务器上不起作用。如果您移动到一个新的服务器,在那里它们被禁用,并且您有任何硬编码的密码,其他人可能会看到您的源代码和硬编码的密码。而且它们使得通过解析器运行XML文件更容易出错