Can I use 'file_put_contents' without being forced to save the file?

I am trying to write some code to alter the header (specifically the <link> elements) in an otherwise standard template and then serve the template as usual. Leaving aside the code to make the change, I think I can do this with something like:

         $file = '../templates/pagetemplate.html.php';
         $file2 = 'path/filename';
         $temp = file_get_contents ($file);

//		code to make the changes to $temp (search and replace)

         $temp2 = file_put_contents($file2, $temp);

         include $file2;

But ‘file_put_contents’ will over-write the original file, which I don’t want to do. I could save it to some ‘dump’ (which is what I’ve shown here), I suppose, but I don’t really need to save it.

It wouldn’t be a disaster, of course, but I’m just wondering if there’s any way around this ?

If you are trying to do what I think you are trying to do, another approach might be easier. That approach being, to include the template file itself.

$something_to_use_in_template = 'foo/bar/baz';
include '../templates/pagetemplate.html.php';

Then, I don’t know if you’re aware but, you can use that variable inside the template file.

<link href="<?php echo $something_to_use_in_template ?>" type="stylesheet">

Of course, I could be completely off-target but that looks like what you might have been trying to do. (:

Thank you for your reply.

Yes, I knew I could use a variable inside the template (I do it a lot). I hadn’t explored that route here because I’m trying to ADD something to the template, when a specific condition is met, that is otherwise absent. It seems to me that in this case I’d have to use an ‘if…else’ conditional and add one thing when the condition is met and (somehow) a blank when it is not. ‘Not’ being much more frequent.

My very first thought was to do it with JS, but then I realised that it wouldn’t work because the additional <link>. elements wouldn’t be available when the page loaded.

Since making the original post I’ve discovered some other changes I need to make to the basic template, so I’m inclined to settle for having a slightly different template already available and just call that when the condition is met. I try not to have a proliferation of page templates, but in this case I think it will be easier after all.

As so often, thinking through the problem in order to submit these posts has helped, along with your reply, to make it clearer for me. Thank you.