Saasaan
Saasaan

Reputation: 91

How to change the HTML page title dynamically generated by PHP code

My PHP code is generating 495 HTML pages from 495 txt files and working correctly. But right now, I'm trying to change it as a way to change the value of title tag dynamically; so I'm trying to replace %TITLE% with $Oneline that is the first line of each txt pages.

I have tried many syntaxes such as prg_replace, str_replace and much more all seems unsuccessful. In fact those lines of codes change nothing on my HTML pages.

To be more clear:

  1. Trying to replace %TITLE% with $Oneline.
  2. $Oneline is the first line of the txt file.

Thanks for any help.

<?php
for ($i = 1; $i <= 495; $i++)
{$j = 1;
$SousrceFile = @fopen($SousrceFile, 'r') ;
$TargetFile = fopen($TargetFile, 'w+') ;
fwrite($TargetFile, "<title>%TITLE%</title>\n");
    while ($Oneline = @fgets($SousrceFile, 4096)) 
    {$j = $j + 1;
        if (strlen($Oneline) !==0)
        {
        $title = $Oneline;
        $newTitle = preg_replace('%TITLE%',  $title, $newTitle,1 );
        ...?>

Upvotes: 2

Views: 401

Answers (3)

Saasaan
Saasaan

Reputation: 91

After I couldn't solve the problem, I moved the retreiving data loop to above of the title and as Aaron suggested at this post It made it quiet simple as bellow:

<?php
for ($i = 1; $i <= 495; $i++)
{$j = 1;
$SousrceFile = @fopen($SousrceFile, 'r');
$TargetFile = fopen($TargetFile, 'w+');
while ($Oneline = @fgets($SousrceFile, 4096)) 
{$j = $j + 1;
if (strlen($Oneline) !==0)
$title = $Oneline;
fwrite($TargetFile, "<title>{$title}</title>\n");
...?>

Upvotes: 0

Philipp Palmtag
Philipp Palmtag

Reputation: 1328

Please take a look at preg_replace(), the parameters are

preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

In your code you are using the variable $title to replace the pattern in $newTitle with a limit of one. I think you want to replace the text in the target file instead.

Update: There are two solutions that come into my mind right now:

  1. Instead of writing your text into the file directly, write it into a variable instead. This variable can be searched by preg_replace() and you can change your title dynamically. After you done that, write the variable into the targe file by e.g. fputs().
  2. Instead of replacing the title, set the title directly where it is needed, when you are writing the header section. Than there is no need for replacing.

I would recommend solution one. You know how to do that?

Upvotes: 2

Caspar Wylie
Caspar Wylie

Reputation: 2833

As far as I can see, $newTitle is not defined prior to pre_replace.

Upvotes: 0

Related Questions