Read contents of a file

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
ternet
New php-forum User
New php-forum User
Posts: 2
Joined: Wed Dec 30, 2020 5:02 am

Wed Dec 30, 2020 5:08 am

Hi,

I have a simple question.
Heres my code:

Code: Select all

<?php

$filename  = "testfile.php";
$contents = file_get_contents($filename);

if (preg_match('~<title>(.*?)</title>~', $contents, $title))
{
	$text = implode(" ",$title);
	echo strip_tags($text);
}


?>
This is the file:

Code: Select all

<html>
<title>Testfile</title>

<body >

<h3><b>This is the headline</b></h3>
<p>And this is some text</p>

</body>
</html>
The code works, however the output (Title) is displayed twice.
Any suggestions to why?

Heres the output:
Testfile Testfile
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 418
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Wed Dec 30, 2020 10:18 am

Even though it's a "simple" question it is confusing to me what you are after. Especially when you say the code works, but it displays it twice?

Sorry stupid me didn't see your whole post.
Life is a fig newton of your imagination! https://www.miniaturephotographer.com
AdoptiveSolution
php-forum GURU
php-forum GURU
Posts: 211
Joined: Wed Jun 15, 2016 8:35 am

Thu Dec 31, 2020 12:06 pm

$title is an array, not a string.

The reason you see the text twice is that the first item in the array is the text with the title tag and the second item is the title text itself.

Have a look :

Code: Select all

<?php
$filename  = "testfile.php";
$contents = file_get_contents($filename);
if ( preg_match( '/<title>(.*?)<\/title>/', $contents, $title ) )
{
	echo '<pre>' . htmlentities( print_r( $title, TRUE ) ) . '</pre>';
	echo '<p>' . htmlentities( $title[0] ) . '</p>';
	echo '<p>' . $title[1] . '</p>';
}
?>
Live Regex test here :
https://www.phpliveregex.com/#tab-preg-match
ternet
New php-forum User
New php-forum User
Posts: 2
Joined: Wed Dec 30, 2020 5:02 am

Thu Dec 31, 2020 1:39 pm

Thanks! Understand.
Worked fine now.
Post Reply