-1

I have a bunch of links. I need to extract the title from them. So, I want to make textarea to paste links and button like "get the title" to extract titles. I made a function to extract the title from one URL. It works fine. I'm a newbie in PHP and I don't know how to detect line break to get urls. Could anyone help me?

This is my code

<?php
 function getTitle($url) {
 $data = file_get_contents($url);
$title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $data, $matches) ? $matches[1] : null;
return $title;
 }

 echo getTitle('http://example.com');
 ?>
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
MMPL1
  • 533
  • 7
  • 21

2 Answers2

2

You can use preg_split() for them.

$urls = $_REQUEST['urlArea'];

function getTitle($url) {
    $data = file_get_contents($url);
    $title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $data, $matches) ? $matches[1] : null;
    return $title;
}

// split by new-line character(\r\n or \r or \n)
$arr_url = preg_split('/\r\n|[\r\n]/', $urls);

foreach($arr_url as $url) {
    echo getTitle($url);
}

EDIT : your function added for full code

Meow Kim
  • 445
  • 4
  • 14
  • Hmm, it seems to work but it doesn't echo any title. My code for now function getTitle($url) { $urls = $_REQUEST['urlArea']; $arr_url = preg_split('/\r\n|[\r\n]/', $urls); foreach($arr_url as $url) { echo getTitle($url); } } – MMPL1 Mar 08 '18 at 08:55
  • you called getTitle() function recursively. I edited my answer with full code – Meow Kim Mar 08 '18 at 09:08
  • Hell yeah! This is what I'm looking for. Thank you so much! – MMPL1 Mar 08 '18 at 09:12
  • @MMPL1 it's my pleasure :) – Meow Kim Mar 08 '18 at 09:12
1

Please try this code. When we get the data by using function file_get_contents we should check the length of that data.

 function get_title($url){
      $str = file_get_contents($url);
      if(strlen($str)>0){
        $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
        preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
        return $title[1];
      }
    }
    //For Example:
 echo get_title("stackoverflow.com/"); 

The output is:

Stack Overflow - Where Developers Learn, Share, & Build Careers
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
  • Well this is exactly what I have for now. I want to paste multiple url's like example.com otherexample.com etc. and then output title's for them example1 title otherexample title – MMPL1 Mar 08 '18 at 08:38