Error Notice: Trying to get property of non-object when getting the title of the page

4

I have a code that should take the title of the page example "Facebook - enter or sign up" but that is giving error in this line

$title = $dom->getElementsByTagName('title')->item('0')->nodeValue;

this is the code:

function website_title($urli) {
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $urli);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// define um usuário agente.
   curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36');
   $html = curl_exec($ch);
   curl_close($ch);

   $dom  = new DOMDocument;
   @$dom->loadHTML($html);

   $title = $dom->getElementsByTagName('title')->item('0')->nodeValue;
   return $title;
}

echo website_title('https://www.facebook.com/');

If anyone can help me, I'm grateful.

    
asked by anonymous 23.03.2016 / 16:36

1 answer

4

You have some errors in your code, the first one is - Never use @ to suppress error messages, this makes your code slower and harder to debug. If you had not put @ you would know the reason for your difficulty.

Second, your specific problem is as follows: You are not going to method loadHTML() no value, basically its $html variable is empty. This happened for a reason, your cURL code did not take into account that Facebook uses https and so the cURL request failed, triggering the whole problem. The code below shows a functional version of your code.

<?php

function website_title($urli) {
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $urli);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// define um usuário agente.
   curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36');
   $html = curl_exec($ch);
   curl_close($ch);

   $dom  = new DOMDocument;
   $dom->loadHTML($html);


   $title = $dom->getElementsByTagName('title')->item('0')->nodeValue;
   return $title;
}

echo website_title('https://www.facebook.com/');

I've already I made a library to make it easier to use cURL, it's very simple, but it can help you.

    
23.03.2016 / 17:24