2016-09-17 54 views
0

由于某种原因,当函数中调用的URL上没有图像时,出现以下错误。PHP CURL致命错误:调用成员函数getAttribute()null

Fatal error: Call to a member function getAttribute() on null in .... on line 29 

,如果他们是没有标题这不会发生,如果没有meta标签不会发生,如果他们没有段落标记它不会发生。它似乎只在没有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

可移植性,安全起见,天知道还有什么,应停止使用短标签! – hanshenrik

+0

我不明白你的意思@hanshenrik。上面没有任何代码使用任何短标签。您是否特别提及的使用或者您是否看到更多? – Bruce

+0

是的,我的意思是那些的。他们由于一系列不同的原因而不好。例如,他们将无法在禁用短标签的服务器上工作。如果您转移到禁用其中的新服务器,并且您有任何硬编码密码,其他人可能会看到您的源代码和硬编码密码。而且它们使得它更易于通过解析器运行XML文件 – hanshenrik

回答

1

使用这种检查让ATTRIB前:

 
    if($node->item(0)->hasAttribute('src')) { 
     $firstimage = $node->item(0)->getAttribute('src'); 
    } else { 
     $firstimage = ""; 
    } 

相关问题