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;
}
?>
可移植性,安全起見,天知道還有什麼,應停止使用短標籤! – hanshenrik
我不明白你的意思@hanshenrik。上面沒有任何代碼使用任何短標籤。您是否特別提及 ?>的使用或者您是否看到更多? – Bruce
是的,我的意思是那些 ?>的。他們由於一系列不同的原因而不好。例如,他們將無法在禁用短標籤的服務器上工作。如果您轉移到禁用其中的新服務器,並且您有任何硬編碼密碼,其他人可能會看到您的源代碼和硬編碼密碼。而且它們使得它更易於通過解析器運行XML文件 – hanshenrik