Error Notice: Trying to get Property of non-object when picking the page title

Asked

Viewed 2,328 times

4

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

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

that 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.

  • Makes a print_r( $dom->getElementsByTagName('title')); puts the result there.

  • OK, here I go to test

  • appeared these errors: <pre>Notice: Trying to get Property of non-object in ... line 143</pre> <pre>Notice: Undefined variable: dom in .......... line 143</pre> <pre>Fatal error: Call to a Member Function getelementsbytagname() on null in ........... line 148 </pre>

1 answer

4


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

Second, your specific problem is the following: You are not passing to the method loadHTML() no value, basically its variable $html this 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 working 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 already made a library to make it easier to use Curl, it is very simple, but it can help you .

  • I understood thank you very much was having this error because of the facebook site the way they use the title of the pages.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.