【发布时间】:2016-09-17 00:37:35
【问题描述】:
由于某种原因,当函数中调用的 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;
}
?>
【问题讨论】:
-
为了便携性、安全性,天知道还有什么,别再使用短标签了!
-
我不明白你的意思@hanshenrik。上面发布的代码都没有使用任何短标签。你是专门指 还是你看到更多?
-
是的,我的意思是那些 ?>的。它们之所以不好,有很多不同的原因。例如,它们不能在禁用短标签的服务器上工作。如果您移动到禁用它们的新服务器,并且您有任何硬编码密码,其他人可能能够看到您的源代码和硬编码密码。它们使通过解析器运行 XML 文件更容易出错