由于某些原因,当函数中调用的url上没有图像时,我收到以下错误。
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;
}
?>
答案 0 :(得分:2)
在获取attrib之前使用此检查:
if($node->item(0)->hasAttribute('src')) { $firstimage = $node->item(0)->getAttribute('src'); } else { $firstimage = ""; }