Jump to content

Reading HTML Title in PHP


otchster

Recommended Posts

I am challenged with the task of writing a PHP script that will prompt the user for a website (ex: yahoo.com). When submitted, the PHP script will somehow open the web page as a file, somehow search the source, find the <title> tag, and return the title of the web page..

 

If someone knows an easier approach to this, I would appreciate it. Opening an entire website as a variable seems like a bit of overkill..

 

 

Heres where I'm at so far, I'm kind of looking for a push in the right direction. I've been googling for awhile now trying to find out how to tackle this, but searching for things like "php, website, title, web page, HTML" hasn't proved too successful..

 

thanks in advance

 

<?php


// Assigns $site from the form text box named "site"
//
$site = $_POST['site'];


$file = fopen($site, "r");

// This needs to open the text-source of the inputted webpage.  
// From here I will search for the <title> tag in the HTML...
//
echo "$file";

echo "<br><hr>";

?>

 

Link to comment
Share on other sites

A simple approach using only string manipulations functions should be:

 

<?php
$data = file_get_contents('http://www.yahoo.com');
$title1 = strpos($data, '<title>') + strlen('<title>');
$title2 = strpos($data, '</title>');
echo substr($data, $title1, $title2 - $title1);
?>

 

Using regex should be better though.

Link to comment
Share on other sites

Regex would do this, seriously o_o

 

$data = file_get_contents("SOME URL");
$pattern = "/<title>([^<]*)<\/title>/";
preg_match($pattern, $data, $matches);
//$matches is an array; $matches[1] will get the the data in the first () or the title
$title = $matches[1];

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.