【问题标题】:PHP CURL Fatal error: Call to a member function getAttribute() on nullPHP CURL 致命错误:在 null 上调用成员函数 getAttribute()
【发布时间】: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 文件更容易出错

标签: php curl


【解决方案1】:

在获取属性之前使用此检查:

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

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 2016-06-06
    • 2015-08-01
    • 2018-06-22
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多